diff --git a/changelog/unreleased/enhancement-ldap-eliminate-read-after-write.md b/changelog/unreleased/enhancement-ldap-eliminate-read-after-write.md new file mode 100644 index 00000000000..109ef8a0801 --- /dev/null +++ b/changelog/unreleased/enhancement-ldap-eliminate-read-after-write.md @@ -0,0 +1,14 @@ +Enhancement: Eliminate redundant LDAP read-after-write on create and update + +The graph LDAP backend no longer re-reads an entry immediately after writing it +just to recover the entry ID for the response. When oCIS generates the ID itself +(GRAPH_LDAP_SERVER_UUID disabled), the create response is now synthesized from the +data already sent to the directory, and update responses are built by folding the +applied modifications onto the entry that was read before the write. This avoids a +round-trip that, against a replicated directory reached through a proxy, could hit +a lagging replica and fail or return stale data. + +When the directory assigns the ID (GRAPH_LDAP_SERVER_UUID enabled), creates keep +the existing read-back, since the generated ID cannot otherwise be recovered. + +https://github.com/owncloud/ocis/pull/12618 diff --git a/services/graph/pkg/identity/ldap.go b/services/graph/pkg/identity/ldap.go index 19f415eb9b1..c8873cc2a01 100644 --- a/services/graph/pkg/identity/ldap.go +++ b/services/graph/pkg/identity/ldap.go @@ -149,6 +149,15 @@ func NewLDAPBackend(lc ldap.Client, config config.LDAP, logger *log.Logger, inst if config.GroupNameAttribute == "" || config.GroupIDAttribute == "" { return nil, errors.New("invalid group attribute mappings") } + + // Octet-string ID attributes (e.g. Active Directory's objectGUID) are assigned by + // the directory server, which requires UseServerUUID=true. With UseServerUUID=false + // oCIS generates the ID and writes it as a string UUID, so an octet-string ID + // attribute would be decoded from raw string bytes and produce a corrupt ID. Reject + // this incompatible combination at startup instead of silently returning bad IDs. + if !config.UseServerUUID && (config.UserIDIsOctetString || config.GroupIDIsOctetString) { + return nil, errors.New("invalid config: octet-string ID attributes require GRAPH_LDAP_SERVER_UUID=true") + } gam := groupAttributeMap{ name: config.GroupNameAttribute, id: config.GroupIDAttribute, @@ -266,10 +275,19 @@ func (i *LDAP) CreateUser(ctx context.Context, user libregraph.User) (*libregrap } } - // Read back user from LDAP to get the generated UUID - e, err := i.getUserByDN(ar.DN, "") - if err != nil { - return nil, err + var e *ldap.Entry + if i.useServerUUID { + // The directory assigns the ID and conn.Add cannot return it, so we must + // read the entry back to recover the generated UUID. + e, err = i.getUserByDN(ar.DN, "") + if err != nil { + return nil, err + } + } else { + // oCIS generated the ID and wrote it into the AddRequest, so everything the + // model builder needs is already in hand — synthesize the entry instead of + // reading it back (avoids a read-after-write against a lagging replica). + e = ldap.NewEntry(ar.DN, attrsFromAddRequest(ar)) } return i.createUserModelFromLDAP(e), nil } @@ -439,11 +457,12 @@ func (i *LDAP) UpdateUser(ctx context.Context, nameOrID string, user libregraph. } } - // Read back user from LDAP to get the generated UUID - e, err = i.getUserByDN(e.DN, "") - if err != nil { - return nil, err - } + // Fold the applied changes onto the pre-read entry instead of reading it back. + // The ID is immutable on update (rejected above) and every field the model builder + // reads is either already on e or in the ModifyRequest just applied, so no + // read-after-write is needed. The rename branch (changeUserName) is handled above + // and keeps its own read-back. + e = applyModifyToEntry(e, &mr) returnUser := i.createUserModelFromLDAP(e) diff --git a/services/graph/pkg/identity/ldap_education_class.go b/services/graph/pkg/identity/ldap_education_class.go index 949e8fef557..2734fdd826f 100644 --- a/services/graph/pkg/identity/ldap_education_class.go +++ b/services/graph/pkg/identity/ldap_education_class.go @@ -89,10 +89,18 @@ func (i *LDAP) CreateEducationClass(ctx context.Context, class libregraph.Educat return nil, err } - // Read back group from LDAP to get the generated UUID - e, err := i.getEducationClassByDN(ar.DN) - if err != nil { - return nil, err + var e *ldap.Entry + if i.useServerUUID { + // The directory assigns the ID and conn.Add cannot return it, so we must + // read the entry back to recover the generated UUID. + e, err = i.getEducationClassByDN(ar.DN) + if err != nil { + return nil, err + } + } else { + // oCIS generated the ID and wrote it into the AddRequest, so synthesize the + // entry from data already in hand instead of reading it back. + e = ldap.NewEntry(ar.DN, attrsFromAddRequest(ar)) } return i.createEducationClassModelFromLDAP(e), nil } @@ -142,7 +150,10 @@ func (i *LDAP) UpdateEducationClass(ctx context.Context, id string, class libreg return nil, ErrReadOnly } - g, err := i.getLDAPGroupByID(id, false) + // Request the full education-class attribute set (classification, externalID, …), + // not just [name, id], so the folded response entry carries everything the model + // builder reads — otherwise a displayName-only update would drop classification. + g, err := i.getEducationClassByID(id, false) if err != nil { return nil, err } @@ -174,12 +185,17 @@ func (i *LDAP) UpdateEducationClass(ctx context.Context, id string, class libreg dn := g.DN + // The externalID lives in the RDN and is changed via ModifyDN, not the ModifyRequest. + // The model builder reads it from the externalID attribute, so we fold it on as an + // attribute replace below (deleteOldRDN=true updates the attribute server-side). + externalIDChanged := false if eID := class.GetExternalId(); eID != "" { if g.GetEqualFoldAttributeValue(i.educationConfig.classAttributeMap.externalID) != eID { dn, err = i.updateClassExternalID(ctx, dn, eID) if err != nil { return nil, err } + externalIDChanged = true } } @@ -198,9 +214,14 @@ func (i *LDAP) UpdateEducationClass(ctx context.Context, id string, class libreg } } - g, err = i.getEducationClassByDN(dn) - if err != nil { - return nil, err + // Fold the applied changes onto the pre-read entry instead of reading it back. + // The externalID rename is modelled as an attribute replace so the returned model + // reflects the new externalID. + g = applyModifyToEntry(g, &mr) + if externalIDChanged { + extRename := ldap.ModifyRequest{DN: dn} + extRename.Replace(i.educationConfig.classAttributeMap.externalID, []string{class.GetExternalId()}) + g = applyModifyToEntry(g, &extRename) } return i.createEducationClassModelFromLDAP(g), nil diff --git a/services/graph/pkg/identity/ldap_education_class_test.go b/services/graph/pkg/identity/ldap_education_class_test.go index d5f23adcfd2..c686d6ad095 100644 --- a/services/graph/pkg/identity/ldap_education_class_test.go +++ b/services/graph/pkg/identity/ldap_education_class_test.go @@ -50,7 +50,11 @@ func TestCreateEducationClass(t *testing.T) { }, nil) - b, err := getMockedBackend(lm, eduConfig, &logger) + // useServerUUID=true keeps the read-back path (the directory assigns the ID), + // which is what this test asserts (Search called once, fixed entry returned). + c := eduConfig + c.UseServerUUID = true + b, err := getMockedBackend(lm, c, &logger) assert.Nil(t, err) assert.NotEqual(t, "", b.educationConfig.classObjectClass) class := libregraph.NewEducationClass() diff --git a/services/graph/pkg/identity/ldap_education_school.go b/services/graph/pkg/identity/ldap_education_school.go index 32edcdf71c2..3737fde7f49 100644 --- a/services/graph/pkg/identity/ldap_education_school.go +++ b/services/graph/pkg/identity/ldap_education_school.go @@ -160,10 +160,18 @@ func (i *LDAP) CreateEducationSchool(ctx context.Context, school libregraph.Educ return nil, err } - // Read back school from LDAP to get the generated UUID - e, err := i.getSchoolByDN(ar.DN) - if err != nil { - return nil, err + var e *ldap.Entry + if i.useServerUUID { + // The directory assigns the ID and conn.Add cannot return it, so we must + // read the entry back to recover the generated UUID. + e, err = i.getSchoolByDN(ar.DN) + if err != nil { + return nil, err + } + } else { + // oCIS generated the ID and wrote it into the AddRequest, so synthesize the + // entry from data already in hand instead of reading it back. + e = ldap.NewEntry(ar.DN, attrsFromAddRequest(ar)) } return i.createSchoolModelFromLDAP(e), nil } @@ -240,7 +248,9 @@ func (i *LDAP) updateDisplayName(ctx context.Context, dn string, providedDisplay // updateSchoolProperties updates the properties (other that displayName) of a school. // It checks if a school number is already taken, before updating the school number -func (i *LDAP) updateSchoolProperties(ctx context.Context, dn string, currentSchool, updatedSchool libregraph.EducationSchool) error { +// updateSchoolProperties applies the ModifyRequest and returns it so the caller can +// fold the applied changes onto the pre-read entry (avoiding a read-after-write). +func (i *LDAP) updateSchoolProperties(ctx context.Context, dn string, currentSchool, updatedSchool libregraph.EducationSchool) (*ldap.ModifyRequest, error) { logger := i.logger.SubloggerWithRequestID(ctx) mr := ldap.NewModifyRequest(dn, nil) @@ -248,7 +258,7 @@ func (i *LDAP) updateSchoolProperties(ctx context.Context, dn string, currentSch if *updatedSchoolNumber != "" && currentSchool.GetSchoolNumber() != *updatedSchoolNumber { _, err := i.getSchoolByNumber(*updatedSchoolNumber) if err == nil { - return errSchoolNumberExists + return nil, errSchoolNumberExists } mr.Replace(i.educationConfig.schoolAttributeMap.schoolNumber, []string{*updatedSchoolNumber}) } @@ -267,10 +277,10 @@ func (i *LDAP) updateSchoolProperties(ctx context.Context, dn string, currentSch if err := i.conn.Modify(mr); err != nil { logger.Debug().Err(err).Msg("error updating school number") - return err + return nil, err } - return nil + return mr, nil } // UpdateEducationSchool updates the supplied school in the identity backend @@ -287,6 +297,11 @@ func (i *LDAP) UpdateEducationSchool(ctx context.Context, numberOrID string, sch } currentSchool := i.createSchoolModelFromLDAP(e) + // Fold the applied changes onto the pre-read entry instead of reading it back. + // updateDisplayName mutates the RDN via ModifyDN; the model builder reads displayName + // from the attribute, so we model the rename as a displayName attribute replace. + // updateSchoolProperties returns the ModifyRequest it applied so we can fold it on. + fold := ldap.NewModifyRequest(e.DN, nil) switch i.updateEducationSchoolOperation(school, *currentSchool) { case tooManyValues: return nil, fmt.Errorf("school name and school number cannot be updated in the same request") @@ -297,17 +312,16 @@ func (i *LDAP) UpdateEducationSchool(ctx context.Context, numberOrID string, sch if err := i.updateDisplayName(ctx, e.DN, school.GetDisplayName()); err != nil { return nil, err } + fold.Replace(i.educationConfig.schoolAttributeMap.displayName, []string{school.GetDisplayName()}) case schoolPropertiesUpdated: - if err := i.updateSchoolProperties(ctx, e.DN, *currentSchool, school); err != nil { + mr, err := i.updateSchoolProperties(ctx, e.DN, *currentSchool, school) + if err != nil { return nil, err } + fold.Changes = mr.Changes } - // Read back school from LDAP - e, err = i.getSchoolByNumberOrID(i.getID(e)) - if err != nil { - return nil, err - } + e = applyModifyToEntry(e, fold) return i.createSchoolModelFromLDAP(e), nil } diff --git a/services/graph/pkg/identity/ldap_education_school_test.go b/services/graph/pkg/identity/ldap_education_school_test.go index 526b746eff8..5367094b37e 100644 --- a/services/graph/pkg/identity/ldap_education_school_test.go +++ b/services/graph/pkg/identity/ldap_education_school_test.go @@ -54,13 +54,6 @@ var schoolEntry1 = ldap.NewEntry("ou=Test School1", "ocEducationSchoolNumber": {"0042"}, "owncloudUUID": {"hijk-defg"}, }) -var schoolEntryWithTermination = ldap.NewEntry("ou=Test School", - map[string][]string{ - "ou": {"Test School"}, - "ocEducationSchoolNumber": {"0123"}, - "owncloudUUID": {"abcd-defg"}, - "ocEducationSchoolTerminationTimestamp": {"20420131120000Z"}, - }) var ( filterSchoolSearchByIdExisting = "(&(objectClass=ocEducationSchool)(|(owncloudUUID=abcd-defg)(ocEducationSchoolNumber=abcd-defg)))" @@ -177,7 +170,11 @@ func TestCreateEducationSchool(t *testing.T) { Entries: []*ldap.Entry{schoolEntry}, }, nil) - b, err := getMockedBackend(lm, eduConfig, &logger) + // useServerUUID=true keeps the read-back path (the directory assigns the ID), + // which is what this test asserts (fixed entry returned with a known id). + c := eduConfig + c.UseServerUUID = true + b, err := getMockedBackend(lm, c, &logger) assert.Nil(t, err) assert.NotEqual(t, "", b.educationConfig.schoolObjectClass) @@ -218,6 +215,7 @@ func TestUpdateEducationSchoolTerminationDate(t *testing.T) { return false } lm.On("Modify", mock.MatchedBy(ldapSchoolTerminationRequestMatcher)).Return(nil) + // Single pre-read; the termination Replace is folded onto it (no read-back). lm.On("Search", mock.Anything). Return( &ldap.SearchResult{ @@ -225,13 +223,6 @@ func TestUpdateEducationSchoolTerminationDate(t *testing.T) { }, nil). Once() - lm.On("Search", mock.Anything). - Return( - &ldap.SearchResult{ - Entries: []*ldap.Entry{schoolEntryWithTermination}, - }, - nil). - Once() b, err := getMockedBackend(lm, eduConfig, &logger) assert.Nil(t, err) @@ -240,7 +231,7 @@ func TestUpdateEducationSchoolTerminationDate(t *testing.T) { terminationTime := time.Date(2042, time.January, 31, 12, 0, 0, 0, time.UTC) school.SetTerminationDate(terminationTime) resSchool, err := b.UpdateEducationSchool(context.Background(), "abcd-defg", *school) - lm.AssertNumberOfCalls(t, "Search", 2) + lm.AssertNumberOfCalls(t, "Search", 1) assert.Nil(t, err) assert.NotNil(t, resSchool) assert.Equal(t, "Test School", resSchool.GetDisplayName()) diff --git a/services/graph/pkg/identity/ldap_education_user.go b/services/graph/pkg/identity/ldap_education_user.go index e79ddc67c87..9a8b0e6b156 100644 --- a/services/graph/pkg/identity/ldap_education_user.go +++ b/services/graph/pkg/identity/ldap_education_user.go @@ -44,10 +44,18 @@ func (i *LDAP) CreateEducationUser(ctx context.Context, user libregraph.Educatio return nil, err } - // Read back user from LDAP to get the generated UUID - e, err := i.getEducationUserByDN(ar.DN) - if err != nil { - return nil, err + var e *ldap.Entry + if i.useServerUUID { + // The directory assigns the ID and conn.Add cannot return it, so we must + // read the entry back to recover the generated UUID. + e, err = i.getEducationUserByDN(ar.DN) + if err != nil { + return nil, err + } + } else { + // oCIS generated the ID and wrote it into the AddRequest, so synthesize the + // entry from data already in hand instead of reading it back. + e = ldap.NewEntry(ar.DN, attrsFromAddRequest(ar)) } return i.createEducationUserModelFromLDAP(e), nil } @@ -170,11 +178,11 @@ func (i *LDAP) UpdateEducationUser(ctx context.Context, id string, user libregra } } - // Read back user from LDAP to get the generated UUID - e, err = i.getEducationUserByDN(e.DN) - if err != nil { - return nil, err - } + // Fold the applied changes onto the pre-read entry instead of reading it back. + // The ID is immutable on update (rejected above) and every field the model builder + // reads is either already on e or in the ModifyRequest just applied. The rename + // branch (changeUserName) is handled above and keeps its own read-back. + e = applyModifyToEntry(e, &mr) returnUser := i.createEducationUserModelFromLDAP(e) diff --git a/services/graph/pkg/identity/ldap_education_user_test.go b/services/graph/pkg/identity/ldap_education_user_test.go index b26f57eef8b..74c439b1b82 100644 --- a/services/graph/pkg/identity/ldap_education_user_test.go +++ b/services/graph/pkg/identity/ldap_education_user_test.go @@ -97,7 +97,11 @@ var sr3 *ldap.SearchRequest = &ldap.SearchRequest{ func TestCreateEducationUser(t *testing.T) { lm := &mocks.Client{} - b, err := getMockedBackend(lm, eduConfig, &logger) + // useServerUUID=true keeps the read-back path (the directory assigns the ID), + // which is what this test asserts (Search called once, fixed entry returned). + c := eduConfig + c.UseServerUUID = true + b, err := getMockedBackend(lm, c, &logger) assert.Nil(t, err) //assert.NotEqual(t, "", b.educationConfig.schoolObjectClass) lm.On("Add", mock.Anything).Return(nil) diff --git a/services/graph/pkg/identity/ldap_group.go b/services/graph/pkg/identity/ldap_group.go index 727be10f9a6..efd6f49c844 100644 --- a/services/graph/pkg/identity/ldap_group.go +++ b/services/graph/pkg/identity/ldap_group.go @@ -220,10 +220,18 @@ func (i *LDAP) CreateGroup(ctx context.Context, group libregraph.Group) (*libreg } } - // Read back group from LDAP to get the generated UUID - e, err := i.getGroupByDN(ar.DN) - if err != nil { - return nil, err + var e *ldap.Entry + if i.useServerUUID { + // The directory assigns the ID and conn.Add cannot return it, so we must + // read the entry back to recover the generated UUID. + e, err = i.getGroupByDN(ar.DN) + if err != nil { + return nil, err + } + } else { + // oCIS generated the ID and wrote it into the AddRequest, so synthesize the + // entry from data already in hand instead of reading it back. + e = ldap.NewEntry(ar.DN, attrsFromAddRequest(ar)) } return i.createGroupModelFromLDAP(e), nil } @@ -462,7 +470,7 @@ func (i *LDAP) groupToLDAPAttrValues(group libregraph.Group) (map[string][]strin attrs["objectClass"] = append(attrs["objectClass"], i.groupAdditionalObjectClasses...) if !i.useServerUUID { - attrs["owncloudUUID"] = []string{uuid.Must(uuid.NewV4()).String()} + attrs[i.groupAttributeMap.id] = []string{uuid.Must(uuid.NewV4()).String()} attrs["objectClass"] = append(attrs["objectClass"], "owncloud") } @@ -490,7 +498,7 @@ func (i *LDAP) getLDAPGroupByNameOrID(nameOrID string, requestMembers bool) (*ld if err == nil { filter = fmt.Sprintf("(|(%s=%s)(%s=%s))", i.groupAttributeMap.name, ldap.EscapeFilter(nameOrID), i.groupAttributeMap.id, idString) } else { - filter = fmt.Sprintf("(%s=%s)", i.userAttributeMap.userName, ldap.EscapeFilter(nameOrID)) + filter = fmt.Sprintf("(%s=%s)", i.groupAttributeMap.name, ldap.EscapeFilter(nameOrID)) } return i.getLDAPGroupByFilter(filter, requestMembers) } diff --git a/services/graph/pkg/identity/ldap_test.go b/services/graph/pkg/identity/ldap_test.go index 132d7e342ad..75dd1a9026b 100644 --- a/services/graph/pkg/identity/ldap_test.go +++ b/services/graph/pkg/identity/ldap_test.go @@ -460,8 +460,12 @@ func TestUpdateUser(t *testing.T) { DN: "uid=oldName", Attributes: []*ldap.EntryAttribute{ { - Name: "displayname", - Values: []string{"oldmail@example.org"}, + Name: lconfig.UserDisplayNameAttribute, + Values: []string{"testUser"}, + }, + { + Name: lconfig.UserNameAttribute, + Values: []string{"testUser"}, }, { Name: "entryUUID", @@ -482,54 +486,6 @@ func TestUpdateUser(t *testing.T) { nil, }, }, - { - funcName: "Search", - args: []interface{}{ - &ldap.SearchRequest{ - BaseDN: "uid=oldName", - Scope: 0, - DerefAliases: 0, - SizeLimit: 1, - TimeLimit: 0, - TypesOnly: false, - Filter: "(objectClass=inetOrgPerson)", - Attributes: ldapUserAttributes, - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=oldName", - Attributes: []*ldap.EntryAttribute{ - { - Name: lconfig.UserIDAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEmailAttribute, - Values: []string{"testuser@example.org"}, - }, - { - Name: lconfig.UserDisplayNameAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserNameAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEnabledAttribute, - Values: []string{""}, - }, - }, - }, - }, - }, - nil, - }, - }, { funcName: "Modify", args: []interface{}{ @@ -590,7 +546,11 @@ func TestUpdateUser(t *testing.T) { DN: "uid=oldName", Attributes: []*ldap.EntryAttribute{ { - Name: "displayname", + Name: lconfig.UserDisplayNameAttribute, + Values: []string{"oldName"}, + }, + { + Name: lconfig.UserNameAttribute, Values: []string{"testUser"}, }, { @@ -612,54 +572,6 @@ func TestUpdateUser(t *testing.T) { nil, }, }, - { - funcName: "Search", - args: []interface{}{ - &ldap.SearchRequest{ - BaseDN: "uid=oldName", - Scope: 0, - DerefAliases: 0, - SizeLimit: 1, - TimeLimit: 0, - TypesOnly: false, - Filter: "(objectClass=inetOrgPerson)", - Attributes: ldapUserAttributes, - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=oldName", - Attributes: []*ldap.EntryAttribute{ - { - Name: lconfig.UserIDAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEmailAttribute, - Values: []string{"testuser@example.org"}, - }, - { - Name: lconfig.UserDisplayNameAttribute, - Values: []string{"newName"}, - }, - { - Name: lconfig.UserNameAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEnabledAttribute, - Values: []string{""}, - }, - }, - }, - }, - }, - nil, - }, - }, { funcName: "Modify", args: []interface{}{ @@ -910,8 +822,12 @@ func TestUpdateUser(t *testing.T) { DN: "uid=name", Attributes: []*ldap.EntryAttribute{ { - Name: "displayname", - Values: []string{"testuser@example.org"}, + Name: lconfig.UserDisplayNameAttribute, + Values: []string{"testUser"}, + }, + { + Name: lconfig.UserNameAttribute, + Values: []string{"testUser"}, }, { Name: "entryUUID", @@ -932,54 +848,6 @@ func TestUpdateUser(t *testing.T) { nil, }, }, - { - funcName: "Search", - args: []interface{}{ - &ldap.SearchRequest{ - BaseDN: "uid=name", - Scope: 0, - DerefAliases: 0, - SizeLimit: 1, - TimeLimit: 0, - TypesOnly: false, - Filter: "(objectClass=inetOrgPerson)", - Attributes: ldapUserAttributes, - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=name", - Attributes: []*ldap.EntryAttribute{ - { - Name: lconfig.UserIDAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEmailAttribute, - Values: []string{"testuser@example.org"}, - }, - { - Name: lconfig.UserDisplayNameAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserNameAttribute, - Values: []string{"testUser"}, - }, - { - Name: lconfig.UserEnabledAttribute, - Values: []string{"FALSE"}, - }, - }, - }, - }, - }, - nil, - }, - }, { funcName: "Modify", args: []interface{}{ @@ -1040,9 +908,13 @@ func TestUpdateUser(t *testing.T) { { DN: "uid=name", Attributes: []*ldap.EntryAttribute{ + { + Name: "uid", + Values: []string{"testUser"}, + }, { Name: "displayname", - Values: []string{"testuser@example.org"}, + Values: []string{"testUser"}, }, { Name: "entryUUID", @@ -1114,58 +986,6 @@ func TestUpdateUser(t *testing.T) { }, returns: []interface{}{nil}, }, - { - funcName: "Modify", - args: []interface{}{ - &ldap.ModifyRequest{ - DN: "uid=name", - Changes: []ldap.Change(nil), - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{nil}, - }, - { - funcName: "Search", - args: []interface{}{ - ldap.NewSearchRequest( - "uid=name", - ldap.ScopeBaseObject, - ldap.NeverDerefAliases, 1, 0, false, - "(objectClass=inetOrgPerson)", - ldapUserAttributes, - []ldap.Control(nil), - ), - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=name", - Attributes: []*ldap.EntryAttribute{ - { - Name: "uid", - Values: []string{"testUser"}, - }, - { - Name: "displayname", - Values: []string{"testUser"}, - }, - { - Name: "entryUUID", - Values: []string{"testUser"}, - }, - { - Name: "mail", - Values: []string{"testuser@example.org"}, - }, - }, - }, - }, - }, - nil, - }, - }, }, }, { @@ -1207,9 +1027,13 @@ func TestUpdateUser(t *testing.T) { { DN: "uid=name", Attributes: []*ldap.EntryAttribute{ + { + Name: "uid", + Values: []string{"testUser"}, + }, { Name: "displayname", - Values: []string{"testuser@example.org"}, + Values: []string{"testUser"}, }, { Name: "entryUUID", @@ -1281,58 +1105,6 @@ func TestUpdateUser(t *testing.T) { }, returns: []interface{}{nil}, }, - { - funcName: "Modify", - args: []interface{}{ - &ldap.ModifyRequest{ - DN: "uid=name", - Changes: []ldap.Change(nil), - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{nil}, - }, - { - funcName: "Search", - args: []interface{}{ - ldap.NewSearchRequest( - "uid=name", - ldap.ScopeBaseObject, - ldap.NeverDerefAliases, 1, 0, false, - "(objectClass=inetOrgPerson)", - ldapUserAttributes, - []ldap.Control(nil), - ), - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=name", - Attributes: []*ldap.EntryAttribute{ - { - Name: "uid", - Values: []string{"testUser"}, - }, - { - Name: "displayname", - Values: []string{"testUser"}, - }, - { - Name: "entryUUID", - Values: []string{"testUser"}, - }, - { - Name: "mail", - Values: []string{"testuser@example.org"}, - }, - }, - }, - }, - }, - nil, - }, - }, }, }, { @@ -1373,9 +1145,13 @@ func TestUpdateUser(t *testing.T) { { DN: "uid=name", Attributes: []*ldap.EntryAttribute{ + { + Name: "uid", + Values: []string{"testUser"}, + }, { Name: "displayname", - Values: []string{"testuser@example.org"}, + Values: []string{"testUser"}, }, { Name: "entryUUID", @@ -1415,62 +1191,6 @@ func TestUpdateUser(t *testing.T) { }, returns: []interface{}{nil}, }, - { - funcName: "Modify", - args: []interface{}{ - &ldap.ModifyRequest{ - DN: "uid=name", - Changes: []ldap.Change(nil), - Controls: []ldap.Control(nil), - }, - }, - returns: []interface{}{nil}, - }, - { - funcName: "Search", - args: []interface{}{ - ldap.NewSearchRequest( - "uid=name", - ldap.ScopeBaseObject, - ldap.NeverDerefAliases, 1, 0, false, - "(objectClass=inetOrgPerson)", - ldapUserAttributes, - []ldap.Control(nil), - ), - }, - returns: []interface{}{ - &ldap.SearchResult{ - Entries: []*ldap.Entry{ - { - DN: "uid=name", - Attributes: []*ldap.EntryAttribute{ - { - Name: "uid", - Values: []string{"testUser"}, - }, - { - Name: "displayname", - Values: []string{"testUser"}, - }, - { - Name: "entryUUID", - Values: []string{"testUser"}, - }, - { - Name: "mail", - Values: []string{"testuser@example.org"}, - }, - { - Name: lconfig.UserTypeAttribute, - Values: []string{"Member"}, - }, - }, - }, - }, - }, - nil, - }, - }, }, }, } diff --git a/services/graph/pkg/identity/ldap_writeback.go b/services/graph/pkg/identity/ldap_writeback.go new file mode 100644 index 00000000000..19892eeafc0 --- /dev/null +++ b/services/graph/pkg/identity/ldap_writeback.go @@ -0,0 +1,125 @@ +package identity + +import ( + "strings" + + "github.com/go-ldap/ldap/v3" +) + +// attrsFromAddRequest flattens the attributes of an *ldap.AddRequest into the +// map[string][]string shape that ldap.NewEntry expects. It is used to synthesize +// the response entry from data already in hand, avoiding a read-after-write when +// oCIS generated the entry's ID itself (useServerUUID=false). +func attrsFromAddRequest(ar *ldap.AddRequest) map[string][]string { + attrs := make(map[string][]string, len(ar.Attributes)) + for _, a := range ar.Attributes { + vals := make([]string, len(a.Vals)) + copy(vals, a.Vals) + attrs[a.Type] = vals + } + return attrs +} + +// applyModifyToEntry returns a copy of base with the changes from mr folded on +// (Replace / Add / Delete). It never mutates base. Attribute names are matched +// case-insensitively, consistent with ldap.Entry's GetEqualFold* accessors, so +// folding never produces a duplicate attribute entry that differs only in case. +// +// It is used to synthesize the response entry after an update from the pre-read +// entry plus the ModifyRequest being persisted, avoiding a read-after-write. +func applyModifyToEntry(base *ldap.Entry, mr *ldap.ModifyRequest) *ldap.Entry { + if base == nil { + return nil + } + if mr == nil { + mr = &ldap.ModifyRequest{DN: base.DN} + } + // Deep-copy base into a name->values map so we never touch the original. + attrs := make(map[string][]string, len(base.Attributes)) + // order preserves the original attribute order, with new attributes appended. + order := make([]string, 0, len(base.Attributes)) + index := make(map[string]string, len(base.Attributes)) // fold-key -> stored name + for _, a := range base.Attributes { + vals := make([]string, len(a.Values)) + copy(vals, a.Values) + attrs[a.Name] = vals + order = append(order, a.Name) + index[strings.ToLower(a.Name)] = a.Name + } + + // name resolves the stored attribute name for attrType case-insensitively, + // registering a new attribute (preserving the request's casing) if none matches. + name := func(attrType string) string { + if n, ok := index[strings.ToLower(attrType)]; ok { + return n + } + index[strings.ToLower(attrType)] = attrType + order = append(order, attrType) + return attrType + } + + for _, change := range mr.Changes { + attrType := change.Modification.Type + vals := change.Modification.Vals + switch change.Operation { + case ldap.ReplaceAttribute: + n := name(attrType) + cp := make([]string, len(vals)) + copy(cp, vals) + attrs[n] = cp + case ldap.AddAttribute: + n := name(attrType) + attrs[n] = append(attrs[n], vals...) + case ldap.DeleteAttribute: + if n, ok := index[strings.ToLower(attrType)]; ok { + if len(vals) == 0 { + // whole-attribute delete + delete(attrs, n) + } else { + kept := removeValues(attrs[n], vals) + if len(kept) == 0 { + // the last value was removed; a real server drops the attribute + delete(attrs, n) + } else { + attrs[n] = kept + } + } + } + } + } + + dn := base.DN + if mr.DN != "" { + dn = mr.DN + } + result := ldap.NewEntry(dn, nil) + result.Attributes = make([]*ldap.EntryAttribute, 0, len(order)) + for _, n := range order { + v, ok := attrs[n] + if !ok { + // deleted attribute + continue + } + result.Attributes = append(result.Attributes, ldap.NewEntryAttribute(n, v)) + } + return result +} + +// removeValues returns have with every element of remove stripped out. +func removeValues(have, remove []string) []string { + if len(have) == 0 { + return have + } + drop := make(map[string]struct{}, len(remove)) + for _, r := range remove { + drop[r] = struct{}{} + } + kept := make([]string, 0, len(have)) + for _, v := range have { + if _, ok := drop[v]; ok { + continue + } + kept = append(kept, v) + } + return kept +} diff --git a/services/graph/pkg/identity/ldap_writeback_test.go b/services/graph/pkg/identity/ldap_writeback_test.go new file mode 100644 index 00000000000..4eb66218e51 --- /dev/null +++ b/services/graph/pkg/identity/ldap_writeback_test.go @@ -0,0 +1,741 @@ +package identity + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/go-ldap/ldap/v3" + libregraph "github.com/owncloud/libre-graph-api-go" + "github.com/owncloud/ocis/v2/ocis-pkg/log" + "github.com/owncloud/ocis/v2/services/graph/pkg/identity/mocks" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" +) + +func TestAttrsFromAddRequest(t *testing.T) { + ar := ldap.NewAddRequest("uid=alice,ou=people,dc=test", nil) + ar.Attribute("uid", []string{"alice"}) + ar.Attribute("displayname", []string{"Alice Example"}) + ar.Attribute("mail", []string{"alice@example.org", "a@example.org"}) + + attrs := attrsFromAddRequest(ar) + + assert.Equal(t, []string{"alice"}, attrs["uid"]) + assert.Equal(t, []string{"Alice Example"}, attrs["displayname"]) + assert.Equal(t, []string{"alice@example.org", "a@example.org"}, attrs["mail"]) + + // round-trips through ldap.NewEntry with case-insensitive lookup + e := ldap.NewEntry(ar.DN, attrs) + assert.Equal(t, ar.DN, e.DN) + assert.Equal(t, "alice", e.GetEqualFoldAttributeValue("UID")) + assert.Equal(t, "Alice Example", e.GetEqualFoldAttributeValue("displayName")) + assert.Equal(t, []string{"alice@example.org", "a@example.org"}, e.GetEqualFoldAttributeValues("mail")) +} + +// TestAttrsFromAddRequestDoesNotAliasRequest guards against attrsFromAddRequest +// returning slices that alias ar.Attributes[].Vals: mutating the returned map must +// never change the AddRequest's own values, and vice versa. +func TestAttrsFromAddRequestDoesNotAliasRequest(t *testing.T) { + ar := ldap.NewAddRequest("uid=alice,ou=people,dc=test", nil) + ar.Attribute("mail", []string{"alice@example.org"}) + + attrs := attrsFromAddRequest(ar) + attrs["mail"][0] = "mutated@example.org" + + assert.Equal(t, []string{"alice@example.org"}, ar.Attributes[0].Vals) +} + +func TestApplyModifyToEntry(t *testing.T) { + base := ldap.NewEntry("uid=alice,ou=people,dc=test", map[string][]string{ + "uid": {"alice"}, + "displayname": {"Alice Example"}, + "mail": {"alice@example.org"}, + "member": {"cn=a", "cn=b"}, + }) + + t.Run("Replace overwrites existing attribute", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Replace("displayname", []string{"Alice New"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, "Alice New", got.GetEqualFoldAttributeValue("displayname")) + }) + + t.Run("Replace adds a not-yet-present attribute", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Replace("givenname", []string{"Alice"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, "Alice", got.GetEqualFoldAttributeValue("givenname")) + }) + + t.Run("Add appends to existing attribute", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Add("member", []string{"cn=c"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, []string{"cn=a", "cn=b", "cn=c"}, got.GetEqualFoldAttributeValues("member")) + }) + + t.Run("Delete whole attribute", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Delete("mail", []string{}) + + got := applyModifyToEntry(base, mr) + assert.Empty(t, got.GetEqualFoldAttributeValues("mail")) + }) + + t.Run("Delete specific value", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Delete("member", []string{"cn=a"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, []string{"cn=b"}, got.GetEqualFoldAttributeValues("member")) + }) + + t.Run("Delete last remaining value drops the attribute", func(t *testing.T) { + single := ldap.NewEntry(base.DN, map[string][]string{ + "member": {"cn=a"}, + }) + mr := &ldap.ModifyRequest{DN: single.DN} + mr.Delete("member", []string{"cn=a"}) + + got := applyModifyToEntry(single, mr) + assert.Empty(t, got.GetEqualFoldAttributeValues("member")) + for _, a := range got.Attributes { + assert.NotEqual(t, "member", strings.ToLower(a.Name), "attribute must be dropped, not left empty") + } + }) + + t.Run("nil ModifyRequest returns base unchanged", func(t *testing.T) { + got := applyModifyToEntry(base, nil) + assert.Equal(t, base.DN, got.DN) + assert.Equal(t, "Alice Example", got.GetEqualFoldAttributeValue("displayname")) + assert.Equal(t, []string{"cn=a", "cn=b"}, got.GetEqualFoldAttributeValues("member")) + }) + + t.Run("nil base returns nil", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: "uid=alice,ou=people,dc=test"} + mr.Replace("displayname", []string{"Alice New"}) + + got := applyModifyToEntry(nil, mr) + assert.Nil(t, got) + }) + + t.Run("case-insensitive match creates no duplicate", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Replace("DisplayName", []string{"Alice Caps"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, "Alice Caps", got.GetEqualFoldAttributeValue("displayname")) + // exactly one attribute entry whose name folds to displayname + count := 0 + for _, a := range got.Attributes { + if strings.EqualFold(a.Name, "displayname") { + count++ + } + } + assert.Equal(t, 1, count) + }) + + t.Run("base is never mutated", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Replace("displayname", []string{"Mutated"}) + mr.Add("member", []string{"cn=z"}) + mr.Delete("mail", []string{}) + + _ = applyModifyToEntry(base, mr) + assert.Equal(t, "Alice Example", base.GetEqualFoldAttributeValue("displayname")) + assert.Equal(t, []string{"cn=a", "cn=b"}, base.GetEqualFoldAttributeValues("member")) + assert.Equal(t, "alice@example.org", base.GetEqualFoldAttributeValue("mail")) + }) + + t.Run("Replace populates ByteValues for raw accessors", func(t *testing.T) { + mr := &ldap.ModifyRequest{DN: base.DN} + mr.Replace("displayname", []string{"Raw Value"}) + + got := applyModifyToEntry(base, mr) + assert.Equal(t, []byte("Raw Value"), got.GetEqualFoldRawAttributeValue("displayname")) + }) +} + +// TestCreateUserSynthesizesWhenNotServerUUID asserts that with useServerUUID=false +// CreateUser builds the response model from the AddRequest instead of reading the +// entry back — i.e. no Search is issued after the Add. +func TestCreateUserSynthesizesWhenNotServerUUID(t *testing.T) { + displayName := "DisplayName" + mail := "user@example" + userName := "user" + surname := "surname" + givenName := "givenName" + userType := "Member" + + l := &mocks.Client{} + // Add succeeds; Search must NOT be called (no read-back). + l.On("Add", mock.Anything).Return(nil) + logger := log.NewLogger(log.Level("debug")) + + user := libregraph.NewUser(displayName, userName) + user.SetMail(mail) + user.SetSurname(surname) + user.SetGivenName(givenName) + user.SetAccountEnabled(true) + user.SetUserType(userType) + + c := lconfig + c.UseServerUUID = false + b, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Nil(t, err) + + newUser, err := b.CreateUser(context.Background(), *user) + assert.Nil(t, err) + assert.Equal(t, displayName, newUser.GetDisplayName()) + assert.Equal(t, mail, newUser.GetMail()) + assert.Equal(t, userName, newUser.GetOnPremisesSamAccountName()) + assert.Equal(t, givenName, newUser.GetGivenName()) + assert.Equal(t, surname, newUser.GetSurname()) + assert.True(t, newUser.GetAccountEnabled()) + assert.Equal(t, userType, newUser.GetUserType()) + // oCIS generated the id and wrote it into the Add; it must be present on the model. + assert.NotEmpty(t, newUser.GetId()) + + l.AssertNotCalled(t, "Search", mock.Anything) +} + +// TestCreateUserSynthesizedModelEqualsReadBack is the regression guard: the model +// CreateUser returns from the synthesize path (useServerUUID=false) must equal the +// model the unchanged builder produces from the entry a read-back would have returned +// — i.e. the server's echo of exactly what oCIS wrote. Eliminating the read-back must +// not change the CreateUser response for any populated field. +func TestCreateUserSynthesizedModelEqualsReadBack(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + user := libregraph.NewUser("DisplayName", "user") + user.SetMail("user@example") + user.SetSurname("surname") + user.SetGivenName("givenName") + user.SetAccountEnabled(true) + user.SetUserType("Member") + + // Capture the AddRequest so we can reproduce the entry a read-back would return. + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + + c := lconfig + c.UseServerUUID = false + b, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Nil(t, err) + + synthUser, err := b.CreateUser(context.Background(), *user) + assert.Nil(t, err) + + // Ground truth: what the old read-back path would have built. A base-scoped search + // on the DN returns exactly the attributes that were written, so the read-back entry + // is ldap.NewEntry over the captured AddRequest. + readBackEntry := ldap.NewEntry(written.DN, attrsFromAddRequest(written)) + readBackModel := b.createUserModelFromLDAP(readBackEntry) + + assert.Equal(t, readBackModel, synthUser) +} + +// TestSynthesizedEntryPopulatesInstancesWithoutSearch is the regression guard for the +// attribute-sourced multi-instance fields. With instanceURLTemplate + +// crossInstanceReferenceTemplate configured and instanceMapperEnabled=false, building a +// user model from a synthesized entry (as the create/update fold paths do) must populate +// user.Instances / CrossInstanceReference AND must not issue a live Search — the codepath +// only searches when instanceMapperEnabled=true, which is mutually exclusive with the +// "no second LDAP call" guarantee (see the design spec's Testing section). +func TestSynthesizedEntryPopulatesInstancesWithoutSearch(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := lconfig + c.UserMemberAttribute = "ocMemberOfInstance" + c.InstanceURLTemplate = "https://{{.Instancename}}.example.org" + c.CrossInstanceReferenceTemplate = "{{.Username}}@{{.Instancename}}" + c.InstanceMapperEnabled = false + + l := &mocks.Client{} + // A non-empty instanceID is required for the instance templates to be parsed. + b, err := NewLDAPBackend(l, c, &logger, "instanceA", "") + assert.Nil(t, err) + + // Synthesized entry as attrsFromAddRequest + ldap.NewEntry would produce, carrying a + // member-of-instance value so the Instances loop runs. + entry := ldap.NewEntry("uid=user,ou=people,dc=test", map[string][]string{ + "uid": {"user"}, + "displayname": {"DisplayName"}, + "mail": {"user@example"}, + "entryUUID": {"abcd-defg"}, + "ocMemberOfInstance": {"instanceA"}, + }) + + model := b.createUserModelFromLDAP(entry) + assert.NotNil(t, model) + assert.NotEmpty(t, model.Instances) + assert.Equal(t, "https://instanceA.example.org", model.Instances[0].GetUrl()) + assert.NotNil(t, model.CrossInstanceReference) + assert.Equal(t, "user@instanceA", model.GetCrossInstanceReference()) + + // instanceMapperEnabled=false → getInstance returns the value verbatim, no Search. + l.AssertNotCalled(t, "Search", mock.Anything) +} + +// TestCreateGroupSynthesizesWhenNotServerUUID asserts CreateGroup builds its response +// from the AddRequest (no read-back) when oCIS generated the id itself. +func TestCreateGroupSynthesizesWhenNotServerUUID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + // oCIS writes the generated group id under the configured GroupIDAttribute, so the + // synthesized entry must carry the id under that attribute for the model builder. + c := lconfig + c.UseServerUUID = false + c.GroupIDAttribute = "owncloudUUID" + + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + + b, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Nil(t, err) + + group := libregraph.NewGroup() + group.SetDisplayName("mygroup") + + newGroup, err := b.CreateGroup(context.Background(), *group) + assert.Nil(t, err) + assert.Equal(t, "mygroup", newGroup.GetDisplayName()) + assert.NotEmpty(t, newGroup.GetId()) + l.AssertNotCalled(t, "Search", mock.Anything) + + // parity with the read-back-derived model + readBackModel := b.createGroupModelFromLDAP(ldap.NewEntry(written.DN, attrsFromAddRequest(written))) + assert.Equal(t, readBackModel, newGroup) +} + +// TestCreateEducationUserSynthesizesWhenNotServerUUID asserts CreateEducationUser +// synthesizes its response (no read-back) when oCIS generated the id itself. +func TestCreateEducationUserSynthesizesWhenNotServerUUID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := eduConfig + c.UseServerUUID = false + + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + + b, err := getMockedBackend(l, c, &logger) + assert.Nil(t, err) + + user := libregraph.NewEducationUser() + user.SetDisplayName("Test User") + user.SetOnPremisesSamAccountName("testuser") + user.SetMail("testuser@example.org") + user.SetPrimaryRole("student") + user.SetUserType("Member") + user.SetAccountEnabled(false) + user.SetExternalID("ext-ernal-id") + + eduUser, err := b.CreateEducationUser(context.Background(), *user) + assert.Nil(t, err) + assert.Equal(t, "Test User", eduUser.GetDisplayName()) + assert.Equal(t, "testuser", eduUser.GetOnPremisesSamAccountName()) + assert.NotEmpty(t, eduUser.GetId()) + l.AssertNotCalled(t, "Search", mock.Anything) + + readBackModel := b.createEducationUserModelFromLDAP(ldap.NewEntry(written.DN, attrsFromAddRequest(written))) + assert.Equal(t, readBackModel, eduUser) +} + +// TestCreateEducationClassSynthesizesWhenNotServerUUID asserts CreateEducationClass +// synthesizes its response (no read-back) when oCIS generated the id itself. +func TestCreateEducationClassSynthesizesWhenNotServerUUID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := eduConfig + c.UseServerUUID = false + c.GroupIDAttribute = "owncloudUUID" + + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + + b, err := getMockedBackend(l, c, &logger) + assert.Nil(t, err) + + class := libregraph.NewEducationClass() + class.SetExternalId("Math0123") + class.SetDisplayName("Math") + class.SetClassification("course") + + resClass, err := b.CreateEducationClass(context.Background(), *class) + assert.Nil(t, err) + assert.Equal(t, "Math", resClass.GetDisplayName()) + assert.Equal(t, "Math0123", resClass.GetExternalId()) + assert.Equal(t, "course", resClass.GetClassification()) + assert.NotEmpty(t, resClass.GetId()) + l.AssertNotCalled(t, "Search", mock.Anything) + + readBackModel := b.createEducationClassModelFromLDAP(ldap.NewEntry(written.DN, attrsFromAddRequest(written))) + assert.Equal(t, readBackModel, resClass) +} + +// TestCreateEducationSchoolSynthesizesWhenNotServerUUID asserts CreateEducationSchool +// synthesizes its response (no read-back) when oCIS generated the id itself. The +// pre-create duplicate-number Search still fires; only the read-back is eliminated. +func TestCreateEducationSchoolSynthesizesWhenNotServerUUID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := eduConfig + c.UseServerUUID = false + + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + // The duplicate-schoolNumber lookup before Add is a subtree search that returns + // "not found" so create proceeds. No base-scoped read-back must follow the Add. + l.On("Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeWholeSubtree + })).Return(&ldap.SearchResult{Entries: []*ldap.Entry{}}, nil) + + b, err := getMockedBackend(l, c, &logger) + assert.Nil(t, err) + + school := libregraph.NewEducationSchool() + school.SetDisplayName("Test School") + school.SetSchoolNumber("0123") + + resSchool, err := b.CreateEducationSchool(context.Background(), *school) + assert.Nil(t, err) + assert.Equal(t, "Test School", resSchool.GetDisplayName()) + assert.Equal(t, "0123", resSchool.GetSchoolNumber()) + assert.NotEmpty(t, resSchool.GetId()) + // no base-scoped read-back on the created school DN + l.AssertNotCalled(t, "Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeBaseObject + })) + + readBackModel := b.createSchoolModelFromLDAP(ldap.NewEntry(written.DN, attrsFromAddRequest(written))) + assert.Equal(t, readBackModel, resSchool) +} + +// TestUpdateUserFoldsNoReadBack asserts a non-rename UpdateUser does not read the +// entry back: it pre-reads once, Modifies, and folds the ModifyRequest onto the +// pre-read entry to build the response. +func TestUpdateUserFoldsNoReadBack(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + preRead := ldap.NewEntry("uid=user,ou=people,dc=test", map[string][]string{ + "uid": {"user"}, + "displayname": {"Old Name"}, + "mail": {"old@example.org"}, + "entryUUID": {"abcd-defg"}, + "userTypeAttribute": {"Member"}, + }) + + l := &mocks.Client{} + // Pre-read (subtree search by name/id) returns the entry once. + l.On("Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeWholeSubtree + })).Return(&ldap.SearchResult{Entries: []*ldap.Entry{preRead}}, nil).Once() + l.On("Modify", mock.Anything).Return(nil) + + b, err := getMockedBackend(l, lconfig, &logger) + assert.Nil(t, err) + + id := "abcd-defg" + newMail := "new@example.org" + update := libregraph.UserUpdate{Mail: &newMail} + update.Id = &id + + got, err := b.UpdateUser(context.Background(), "user", update) + assert.Nil(t, err) + assert.Equal(t, newMail, got.GetMail()) + assert.Equal(t, "Old Name", got.GetDisplayName()) + assert.Equal(t, "abcd-defg", got.GetId()) + + // No base-scoped read-back after the Modify. + l.AssertNotCalled(t, "Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeBaseObject + })) +} + +// TestUpdateEducationUserFoldsNoReadBack asserts a non-rename UpdateEducationUser +// folds the ModifyRequest onto the pre-read entry rather than reading it back. +func TestUpdateEducationUserFoldsNoReadBack(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + preRead := ldap.NewEntry("uid=testuser,ou=people,dc=test", map[string][]string{ + "uid": {"testuser"}, + "displayname": {"Test User"}, + "mail": {"old@example.org"}, + "entryUUID": {"abcd-defg"}, + "userClass": {"student"}, + "userTypeAttribute": {"Member"}, + }) + + l := &mocks.Client{} + // Pre-read by name/id (subtree) returns the entry; no base-scoped read-back after. + l.On("Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeWholeSubtree + })).Return(&ldap.SearchResult{Entries: []*ldap.Entry{preRead}}, nil).Once() + l.On("Modify", mock.Anything).Return(nil) + + b, err := getMockedBackend(l, eduConfig, &logger) + assert.Nil(t, err) + + newMail := "new@example.org" + user := libregraph.NewEducationUser() + user.SetMail(newMail) + + got, err := b.UpdateEducationUser(context.Background(), "testuser", *user) + assert.Nil(t, err) + assert.Equal(t, newMail, got.GetMail()) + assert.Equal(t, "Test User", got.GetDisplayName()) + assert.Equal(t, "abcd-defg", got.GetId()) + + l.AssertNotCalled(t, "Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeBaseObject + })) +} + +// TestUpdateEducationSchoolFoldsNoReadBack asserts UpdateEducationSchool folds the +// applied property changes onto the pre-read entry rather than reading it back. +func TestUpdateEducationSchoolFoldsNoReadBack(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + preRead := ldap.NewEntry("ou=Test School", map[string][]string{ + "ou": {"Test School"}, + "ocEducationSchoolNumber": {"0123"}, + "owncloudUUID": {"abcd-defg"}, + }) + + l := &mocks.Client{} + // Single pre-read; the termination Replace is folded on. No second Search. + l.On("Search", mock.Anything).Return(&ldap.SearchResult{Entries: []*ldap.Entry{preRead}}, nil).Once() + l.On("Modify", mock.Anything).Return(nil) + + b, err := getMockedBackend(l, eduConfig, &logger) + assert.Nil(t, err) + + school := libregraph.NewEducationSchool() + terminationTime := time.Date(2042, time.January, 31, 12, 0, 0, 0, time.UTC) + school.SetTerminationDate(terminationTime) + + got, err := b.UpdateEducationSchool(context.Background(), "abcd-defg", *school) + assert.Nil(t, err) + assert.Equal(t, "Test School", got.GetDisplayName()) + assert.Equal(t, "abcd-defg", got.GetId()) + assert.Equal(t, "0123", got.GetSchoolNumber()) + // the folded termination date is reflected in the response + assert.True(t, got.HasTerminationDate()) + assert.True(t, terminationTime.Equal(got.GetTerminationDate())) + + l.AssertNumberOfCalls(t, "Search", 1) +} + +// TestUpdateEducationClassFoldPreservesClassificationAndExternalID guards the Site 9 +// regression: folding must not drop classification/externalID from the response, even +// on an update that only changes displayName. It also asserts no read-back after Modify. +func TestUpdateEducationClassFoldPreservesClassificationAndExternalID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + // Full education-class entry as getEducationClassByID would return it. + preRead := ldap.NewEntry("ocEducationExternalId=Math0123,ou=groups,dc=test", map[string][]string{ + "cn": {"Math"}, + "entryUUID": {"abcd-defg"}, + "ocEducationExternalId": {"Math0123"}, + "ocEducationClassType": {"course"}, + }) + + l := &mocks.Client{} + l.On("Search", mock.Anything).Return(&ldap.SearchResult{Entries: []*ldap.Entry{preRead}}, nil).Once() + l.On("Modify", mock.Anything).Return(nil) + + b, err := getMockedBackend(l, eduConfig, &logger) + assert.Nil(t, err) + + newName := "Math-2" + class := libregraph.EducationClass{DisplayName: &newName} + + got, err := b.UpdateEducationClass(context.Background(), "abcd-defg", class) + assert.Nil(t, err) + assert.Equal(t, "Math-2", got.GetDisplayName()) + assert.Equal(t, "abcd-defg", got.GetId()) + // classification and externalID must survive a displayName-only update + assert.Equal(t, "course", got.GetClassification()) + assert.Equal(t, "Math0123", got.GetExternalId()) + + l.AssertNotCalled(t, "Search", mock.MatchedBy(func(sr *ldap.SearchRequest) bool { + return sr.Scope == ldap.ScopeBaseObject + })) +} + +// TestCreateGroupSynthesizesWithNonDefaultIDAttribute guards the fix for the +// hardcoded "owncloudUUID" id write: the generated id must be stored under the +// configured GroupIDAttribute, otherwise the synthesized model has no id and +// createGroupModelFromLDAP returns nil (CreateGroup would return (nil, nil)). +func TestCreateGroupSynthesizesWithNonDefaultIDAttribute(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := lconfig + c.UseServerUUID = false + c.GroupIDAttribute = "entryUUID" // non-default: previously the id was written to owncloudUUID only + + var written *ldap.AddRequest + l := &mocks.Client{} + l.On("Add", mock.Anything).Run(func(args mock.Arguments) { + written = args.Get(0).(*ldap.AddRequest) + }).Return(nil) + + b, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Nil(t, err) + + group := libregraph.NewGroup() + group.SetDisplayName("mygroup") + + newGroup, err := b.CreateGroup(context.Background(), *group) + assert.Nil(t, err) + assert.NotNil(t, newGroup) + assert.Equal(t, "mygroup", newGroup.GetDisplayName()) + // the id was written under the configured attribute and survives synthesis + assert.NotEmpty(t, newGroup.GetId()) + assert.NotEmpty(t, written.Attributes) + // the AddRequest carries the id under the configured attribute, not "owncloudUUID" + var idFromConfigured, idFromHardcoded string + for _, a := range written.Attributes { + switch a.Type { + case c.GroupIDAttribute: + if len(a.Vals) > 0 { + idFromConfigured = a.Vals[0] + } + case "owncloudUUID": + if len(a.Vals) > 0 { + idFromHardcoded = a.Vals[0] + } + } + } + assert.NotEmpty(t, idFromConfigured, "id must be written under the configured GroupIDAttribute") + assert.Empty(t, idFromHardcoded, "id must not be written under a hardcoded owncloudUUID") + assert.Equal(t, idFromConfigured, newGroup.GetId()) + l.AssertNotCalled(t, "Search", mock.Anything) +} + +// TestCreateEducationClassSynthesizesWithNonDefaultIDAttribute guards the same +// hardcoded-id fix on the education-class create path, which reuses +// groupToLDAPAttrValues. +func TestCreateEducationClassSynthesizesWithNonDefaultIDAttribute(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := eduConfig + c.UseServerUUID = false + c.GroupIDAttribute = "entryUUID" // non-default + + l := &mocks.Client{} + l.On("Add", mock.Anything).Return(nil) + + b, err := getMockedBackend(l, c, &logger) + assert.Nil(t, err) + + class := libregraph.NewEducationClass() + class.SetExternalId("Math0123") + class.SetDisplayName("Math") + class.SetClassification("course") + + resClass, err := b.CreateEducationClass(context.Background(), *class) + assert.Nil(t, err) + assert.NotNil(t, resClass) + assert.Equal(t, "Math", resClass.GetDisplayName()) + // the id survives synthesis under the configured attribute + assert.NotEmpty(t, resClass.GetId()) + l.AssertNotCalled(t, "Search", mock.Anything) +} + +// TestGetGroupByNameUsesGroupNameAttribute guards the fix for the name-only lookup +// branch of getLDAPGroupByNameOrID, which previously filtered by the user name +// attribute (uid) instead of the group name attribute (cn), so a group could never +// be found by name. That else-branch is reached when filterEscapeUUID errors, which +// happens for a non-UUID name when the id attribute is an octet string. The lookup +// is exercised directly so the assertion isolates the filter, independent of model +// building. +func TestGetGroupByNameUsesGroupNameAttribute(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + + c := lconfig + // Octet-string group IDs require server-assigned UUIDs; this also makes + // filterEscapeUUID error on a non-UUID name, reaching the name-only else branch. + c.UseServerUUID = true + c.GroupIDIsOctetString = true + + var groupSearch *ldap.SearchRequest + l := &mocks.Client{} + l.On("Search", mock.Anything).Run(func(args mock.Arguments) { + groupSearch = args.Get(0).(*ldap.SearchRequest) + }).Return(&ldap.SearchResult{Entries: []*ldap.Entry{groupEntry}}, nil) + + b, err := getMockedBackend(l, c, &logger) + assert.Nil(t, err) + + _, err = b.getLDAPGroupByNameOrID("group", false) + assert.Nil(t, err) + assert.NotNil(t, groupSearch) + // the filter must use the group name attribute (cn), not the user name attribute (uid) + assert.Contains(t, groupSearch.Filter, "("+b.groupAttributeMap.name+"=group)") + assert.NotContains(t, groupSearch.Filter, b.userAttributeMap.userName+"=group") +} + +// TestNewLDAPBackendRejectsOctetStringWithoutServerUUID guards the fail-fast check: +// octet-string ID attributes (server-assigned, e.g. AD objectGUID) are incompatible +// with UseServerUUID=false, where oCIS generates string UUIDs. The combination must +// be rejected at startup rather than silently producing corrupt IDs. +func TestNewLDAPBackendRejectsOctetStringWithoutServerUUID(t *testing.T) { + logger := log.NewLogger(log.Level("debug")) + l := &mocks.Client{} + + t.Run("user octet-string without server UUID is rejected", func(t *testing.T) { + c := lconfig + c.UseServerUUID = false + c.UserIDIsOctetString = true + _, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Error(t, err) + }) + + t.Run("group octet-string without server UUID is rejected", func(t *testing.T) { + c := lconfig + c.UseServerUUID = false + c.GroupIDIsOctetString = true + _, err := NewLDAPBackend(l, c, &logger, "", "") + assert.Error(t, err) + }) + + t.Run("octet-string with server UUID is allowed", func(t *testing.T) { + c := lconfig + c.UseServerUUID = true + c.UserIDIsOctetString = true + c.GroupIDIsOctetString = true + _, err := NewLDAPBackend(l, c, &logger, "", "") + assert.NoError(t, err) + }) + + t.Run("string IDs without server UUID is allowed", func(t *testing.T) { + c := lconfig + c.UseServerUUID = false + c.UserIDIsOctetString = false + c.GroupIDIsOctetString = false + _, err := NewLDAPBackend(l, c, &logger, "", "") + assert.NoError(t, err) + }) +}