diff --git a/README.adoc b/README.adoc index b4ea98c..39218d2 100644 --- a/README.adoc +++ b/README.adoc @@ -226,6 +226,9 @@ func main() { == Library Hacking +=== Reference +Aside from the above (INCREDIBLY brief and perhaps slightly inaccurate) introduction to SecretService concepts, it is recommended to see the `.ref/` directory in git. Notably, the `URLS` file profides several excellent resources for understanding SecretService further. The Dbus specification (first URL in the file) is highly recommended if you are unfamiliar with SecretService internals. + === Tests Many functions are consolidated into a single test due to how dependent certain processes are on other objects. However, all functionality should be covered by test cases and the error string will always be passed through the stack to `go test -v` output. diff --git a/TODO b/TODO index 000477e..fc47707 100644 --- a/TODO +++ b/TODO @@ -1,3 +1 @@ - Benchmarking? -- Do the .Created and .Modified values auto-update by Dbus? --- It seems they do not, so further updates are necessary. Further research is needed, though. diff --git a/collection_funcs.go b/collection_funcs.go index bcb492a..5b24169 100644 --- a/collection_funcs.go +++ b/collection_funcs.go @@ -1,7 +1,6 @@ package gosecret import ( - "strings" "time" "github.com/godbus/dbus/v5" @@ -13,8 +12,6 @@ import ( */ func NewCollection(service *Service, path dbus.ObjectPath) (coll *Collection, err error) { - var splitPath []string - if service == nil { err = ErrNoDbusConn } @@ -29,14 +26,15 @@ func NewCollection(service *Service, path dbus.ObjectPath) (coll *Collection, er Dbus: service.Conn.Object(DbusService, path), }, service: service, - // lastModified: time.Now(), + // LastModified: time.Now(), } - splitPath = strings.Split(string(coll.Dbus.Path()), "/") - - coll.name = splitPath[len(splitPath)-1] - - _, _, err = coll.Modified() + // Populate the struct fields... + // TODO: use channel for errors; condense into a MultiError. + go coll.Locked() + go coll.Label() + go coll.Created() + go coll.Modified() return } @@ -81,6 +79,9 @@ func (c *Collection) CreateItem(label string, attrs map[string]string, secret *S ).Store(&path, &promptPath); err != nil { return } + if err = c.setModify(); err != nil { + return + } if isPrompt(promptPath) { prompt = NewPrompt(c.Conn, promptPath) @@ -93,6 +94,9 @@ func (c *Collection) CreateItem(label string, attrs map[string]string, secret *S } item, err = NewItem(c, path) + if err = item.setCreate(); err != nil { + return + } return } @@ -164,9 +168,25 @@ func (c *Collection) Label() (label string, err error) { label = variant.Value().(string) - if label != c.name { - c.name = label + c.LabelName = label + + return +} + +// Lock will lock an unlocked Collection. It will no-op if the Collection is currently locked. +func (c *Collection) Lock() (err error) { + + if _, err = c.Locked(); err != nil { + return } + if c.IsLocked { + return + } + + if err = c.service.Lock(c); err != nil { + return + } + c.IsLocked = true return } @@ -182,6 +202,7 @@ func (c *Collection) Locked() (isLocked bool, err error) { } isLocked = variant.Value().(bool) + c.IsLocked = isLocked return } @@ -194,6 +215,7 @@ func (c *Collection) Relabel(newLabel string) (err error) { if err = c.Dbus.SetProperty(DbusCollectionLabel, variant); err != nil { return } + c.LabelName = newLabel return } @@ -234,6 +256,38 @@ func (c *Collection) SearchItems(profile string) (items []*Item, err error) { return } +// SetAlias is a thin wrapper/shorthand for Service.SetAlias (but specific to this Collection). +func (c *Collection) SetAlias(alias string) (err error) { + + var call *dbus.Call + + call = c.service.Dbus.Call( + DbusServiceSetAlias, 0, alias, c.Dbus.Path(), + ) + + err = call.Err + + return +} + +// Unlock will unlock a locked Collection. It will no-op if the Collection is currently unlocked. +func (c *Collection) Unlock() (err error) { + + if _, err = c.Locked(); err != nil { + return + } + if !c.IsLocked { + return + } + + if err = c.service.Unlock(c); err != nil { + return + } + c.IsLocked = false + + return +} + // Created returns the time.Time of when a Collection was created. func (c *Collection) Created() (created time.Time, err error) { @@ -256,7 +310,7 @@ func (c *Collection) Created() (created time.Time, err error) { that indicates if the collection has changed since the last call of Collection.Modified. Note that when calling NewCollection, the internal library-tracked modification - time (Collection.lastModified) will be set to the latest modification time of the Collection + time (Collection.LastModified) will be set to the latest modification time of the Collection itself as reported by Dbus rather than the time that NewCollection was called. */ func (c *Collection) Modified() (modified time.Time, isChanged bool, err error) { @@ -274,28 +328,32 @@ func (c *Collection) Modified() (modified time.Time, isChanged bool, err error) if !c.lastModifiedSet { // It's "nil", so set it to modified. We can't check for a zero-value in case Dbus has it as a zero-value. - c.lastModified = modified + c.LastModified = modified c.lastModifiedSet = true } - isChanged = modified.After(c.lastModified) - c.lastModified = modified + isChanged = modified.After(c.LastModified) + c.LastModified = modified return } /* - PathName returns the "real" name of a Collection. - In some cases, the Collection.Label may not be the actual *name* of the collection - (i.e. the label is different from the name used in the Dbus path). - This is a thin wrapper around simply extracting the last item from - the Collection.Dbus.Path(). + setCreate updates the Collection's creation time (as specified by Collection.Created). + It seems that this does not generate automatically. */ -func (c *Collection) PathName() (realName string) { +func (c *Collection) setCreate() (err error) { - var pathSplit []string = strings.Split(string(c.Dbus.Path()), "/") + var t time.Time = time.Now() - realName = pathSplit[len(pathSplit)-1] + if err = c.Dbus.SetProperty(DbusCollectionCreated, uint64(t.Unix())); err != nil { + return + } + c.CreatedAt = t + + if err = c.setModify(); err != nil { + return + } return } @@ -306,7 +364,18 @@ func (c *Collection) PathName() (realName string) { */ func (c *Collection) setModify() (err error) { - err = c.Dbus.SetProperty(DbusCollectionModified, uint64(time.Now().Unix())) + var t time.Time = time.Now() + + err = c.Dbus.SetProperty(DbusCollectionModified, uint64(t.Unix())) + c.LastModified = t + + return +} + +// path is a *very* thin wrapper around Collection.Dbus.Path(). It is needed for LockableObject interface membership. +func (c *Collection) path() (dbusPath dbus.ObjectPath) { + + dbusPath = c.Dbus.Path() return } diff --git a/collection_funcs_test.go b/collection_funcs_test.go index 7145c20..710122e 100644 --- a/collection_funcs_test.go +++ b/collection_funcs_test.go @@ -207,9 +207,9 @@ func TestCollection_Locked(t *testing.T) { } if isLocked, err = collection.Locked(); err != nil { - t.Errorf("failed to get lock status for collection '%v': %v", collection.PathName(), err.Error()) + t.Errorf("failed to get lock status for collection '%v': %v", collection.path(), err.Error()) } else { - t.Logf("collection '%v' lock status: %v", collection.PathName(), isLocked) + t.Logf("collection '%v' lock status: %v", collection.path(), isLocked) } if err = svc.Close(); err != nil { diff --git a/errs.go b/errs.go index 5822fe2..4137daf 100644 --- a/errs.go +++ b/errs.go @@ -12,8 +12,10 @@ var ( ErrInvalidProperty error = errors.New("invalid variant type; cannot convert") // ErrNoDbusConn gets triggered if a connection to Dbus can't be detected. ErrNoDbusConn error = errors.New("no valid dbus connection") - // ErrMissingPaths gets triggered if one or more Dbus object paths are expected but non/not enough are received. + // ErrMissingPaths gets triggered if one or more Dbus object paths are expected but none/not enough are received. ErrMissingPaths error = errors.New("one or more Dbus object paths were expected but an insufficient amount were received") + // ErrMissingObj gets triggered if one or more gosecret-native objects are expected but none/not enough are received. + ErrMissingObj error = errors.New("one or more objects were expected but an insufficient amount were received") // ErrMissingAttrs gets triggered if attributes were expected but not passed. ErrMissingAttrs error = errors.New("attributes must not be empty/nil") // ErrDoesNotExist gets triggered if a Collection, Item, etc. is attempted to be fetched but none exists via the specified identifier. diff --git a/funcs.go b/funcs.go index 2f26d6e..0cba2d2 100644 --- a/funcs.go +++ b/funcs.go @@ -115,3 +115,32 @@ func pathsFromPath(bus dbus.BusObject, path string) (paths []dbus.ObjectPath, er return } + +/* + NameFromPath returns an actual name (as it appears in Dbus) from a dbus.ObjectPath. + Note that you can get any object's dbus.ObjectPath via .Dbus.Path(). - If objectPaths is nil or empty, the Service's own path will be used. -*/ -func (s *Service) Lock(objectPaths ...dbus.ObjectPath) (err error) { +// Lock locks an Unlocked Collection or Item (LockableObject). +func (s *Service) Lock(objects ...LockableObject) (err error) { + var variant dbus.Variant + var toLock []dbus.ObjectPath // We only use these as destinations. var locked []dbus.ObjectPath var prompt *Prompt var promptPath dbus.ObjectPath - if objectPaths == nil || len(objectPaths) == 0 { - objectPaths = []dbus.ObjectPath{s.Dbus.Path()} + if objects == nil || len(objects) == 0 { + err = ErrMissingObj + return } + toLock = make([]dbus.ObjectPath, len(objects)) + + for idx, o := range objects { + toLock[idx] = o.path() + } + variant = dbus.MakeVariant(toLock) + if err = s.Dbus.Call( - DbusServiceLock, 0, objectPaths, + DbusServiceLock, 0, variant, ).Store(&locked, &promptPath); err != nil { return } @@ -257,12 +269,17 @@ func (s *Service) Lock(objectPaths ...dbus.ObjectPath) (err error) { } } + for _, o := range objects { + go o.Locked() + } + return } /* OpenSession returns a pointer to a Session from the Service. It's a convenience function around NewSession. + However, NewService attaches a Session by default at Service.Session so this is likely unnecessary. */ func (s *Service) OpenSession(algo, input string) (session *Session, output dbus.Variant, err error) { @@ -324,6 +341,16 @@ func (s *Service) ReadAlias(alias string) (collection *Collection, err error) { return } +// RemoveAlias is a thin wrapper around Service.SetAlias using the removal method specified there. +func (s *Service) RemoveAlias(alias string) (err error) { + + if err = s.SetAlias(alias, dbus.ObjectPath("/")); err != nil { + return + } + + return +} + /* SearchItems searches all Collection objects and returns all matches based on the map of attributes. */ @@ -411,6 +438,7 @@ func (s *Service) SearchItems(attributes map[string]string) (unlockedItems []*It /* SetAlias sets an alias for an existing Collection. + (You can get its path via .Dbus.Path().) To remove an alias, set objectPath to dbus.ObjectPath("/"). */ func (s *Service) SetAlias(alias string, objectPath dbus.ObjectPath) (err error) { @@ -426,23 +454,30 @@ func (s *Service) SetAlias(alias string, objectPath dbus.ObjectPath) (err error) return } -/* - Unlock unlocks a Locked Service, Collection, etc. - You can usually get objectPath for the object(s) to unlock via .Dbus.Path(). - If objectPaths is nil or empty, the Service's own path will be used. -*/ -func (s *Service) Unlock(objectPaths ...dbus.ObjectPath) (err error) { +// Unlock unlocks a locked Collection or Item (LockableObject). +func (s *Service) Unlock(objects ...LockableObject) (err error) { + var variant dbus.Variant + var toUnlock []dbus.ObjectPath + // We only use these as destinations. var unlocked []dbus.ObjectPath var prompt *Prompt var resultPath dbus.ObjectPath - if objectPaths == nil || len(objectPaths) == 0 { - objectPaths = []dbus.ObjectPath{s.Dbus.Path()} + if objects == nil || len(objects) == 0 { + err = ErrMissingObj + return } + toUnlock = make([]dbus.ObjectPath, len(objects)) + + for idx, o := range objects { + toUnlock[idx] = o.path() + } + variant = dbus.MakeVariant(toUnlock) + if err = s.Dbus.Call( - DbusServiceUnlock, 0, objectPaths, + DbusServiceUnlock, 0, variant, ).Store(&unlocked, &resultPath); err != nil { return } @@ -456,5 +491,17 @@ func (s *Service) Unlock(objectPaths ...dbus.ObjectPath) (err error) { } } + for _, o := range objects { + go o.Locked() + } + + return +} + +// path is a *very* thin wrapper around Service.Dbus.Path(). +func (s *Service) path() (dbusPath dbus.ObjectPath) { + + dbusPath = s.Dbus.Path() + return } diff --git a/service_funcs_test.go b/service_funcs_test.go index f3817f6..e0067c8 100644 --- a/service_funcs_test.go +++ b/service_funcs_test.go @@ -85,7 +85,7 @@ func TestService_Collections(t *testing.T) { } t.Logf( "collection #%v (name '%v', label '%v'): created %v, last modified %v", - idx, c.PathName(), collLabel, created, modified, + idx, c.path(), collLabel, created, modified, ) } } @@ -177,7 +177,7 @@ func TestService_GetCollection(t *testing.T) { if coll, err = svc.GetCollection(defaultCollection); err != nil { t.Errorf("failed to get collection '%v' via Service.GetCollection: %v", defaultCollection, err.Error()) } else { - t.Logf("got collection '%v' via reference '%v'", coll.name, defaultCollection) + t.Logf("got collection '%v' via reference '%v'", coll.LabelName, defaultCollection) } if err = svc.Close(); err != nil { @@ -374,10 +374,11 @@ func TestService_Locking(t *testing.T) { } if collection, err = svc.CreateCollection(collectionName.String()); err != nil { - if err = svc.Close(); err != nil { - t.Errorf("could not close Service.Session: %v", err.Error()) - } t.Errorf("could not create collection '%v': %v", collectionName.String(), err.Error()) + if err = svc.Close(); err != nil { + t.Fatalf("could not close Service.Session: %v", err.Error()) + } + return } else { t.Logf("created collection '%v' at path '%v' successfully", collectionName.String(), string(collection.Dbus.Path())) } @@ -400,23 +401,23 @@ func TestService_Locking(t *testing.T) { // Change the state. if isLocked { - if err = svc.Unlock(collection.Dbus.Path()); err != nil { + if err = collection.Unlock(); err != nil { t.Errorf("could not unlock collection '%v': %v", collectionName.String(), err.Error()) } if stateChangeLock, err = collection.Locked(); err != nil { t.Errorf("received error when checking collection '%v' lock status: %v", collectionName.String(), err.Error()) } - if err = svc.Lock(collection.Dbus.Path()); err != nil { + if err = collection.Lock(); err != nil { t.Errorf("could not lock collection '%v': %v", collectionName.String(), err.Error()) } } else { - if err = svc.Lock(collection.Dbus.Path()); err != nil { + if err = collection.Lock(); err != nil { t.Errorf("could not lock collection '%v': %v", collectionName.String(), err.Error()) } if stateChangeLock, err = collection.Locked(); err != nil { t.Errorf("received error when checking collection '%v' lock status: %v", collectionName.String(), err.Error()) } - if err = svc.Unlock(collection.Dbus.Path()); err != nil { + if err = collection.Unlock(); err != nil { t.Errorf("could not unlock collection '%v': %v", collectionName.String(), err.Error()) } } diff --git a/session_funcs.go b/session_funcs.go index e8210a5..0c4fb8b 100644 --- a/session_funcs.go +++ b/session_funcs.go @@ -42,3 +42,11 @@ func (s *Session) Close() (err error) { return } + +// path is a *very* thin wrapper around Session.Dbus.Path(). +func (s *Session) path() (dbusPath dbus.ObjectPath) { + + dbusPath = s.Dbus.Path() + + return +} diff --git a/types.go b/types.go index 61612f9..582b9ef 100644 --- a/types.go +++ b/types.go @@ -58,6 +58,11 @@ type Prompt struct { *DbusObject } +type LockableObject interface { + Locked() (bool, error) + path() dbus.ObjectPath +} + /* Service is a general SecretService interface, sort of handler for Dbus - it's used for fetching a Session, Collections, etc. https://developer-old.gnome.org/libsecret/0.18/SecretService.html @@ -67,6 +72,8 @@ type Service struct { *DbusObject // Session is a default Session initiated automatically. Session *Session `json:"-"` + // IsLocked indicates if the Service is locked or not. Status updated by Service.Locked. + IsLocked bool `json:"locked"` } /* @@ -82,24 +89,31 @@ type Session struct { /* Collection is an accessor for libsecret collections, which contain multiple Secret Item items. + Do not change any of these values directly; use the associated methods instead. Reference: https://developer-old.gnome.org/libsecret/0.18/SecretCollection.html https://specifications.freedesktop.org/secret-service/latest/ch03.html */ type Collection struct { *DbusObject - // lastModified is unexported because it's important that API users don't change it; it's used by Collection.Modified. - lastModified time.Time + // IsLocked indicates if the Collection is locked or not. Status updated by Collection.Locked. + IsLocked bool `json:"locked"` + // LabelName is the Collection's label (as given by Collection.Label and modified by Collection.Relabel). + LabelName string `json:"label"` + // CreatedAt is when this Collection was created (used by Collection.Created). + CreatedAt time.Time `json:"created"` + // LastModified is when this Item was last changed; it's used by Collection.Modified. + LastModified time.Time `json:"modified"` + // Alias is the Collection's alias (as handled by Service.ReadAlias and Service.SetAlias). + Alias string `json:"alias"` // lastModifiedSet is unexported; it's only used to determine if this is a first-initialization of the modification time or not. lastModifiedSet bool - // name is used for the Collection's name/label so the Dbus path doesn't need to be parsed all the time. - name string // service tracks the Service this Collection was created from. service *Service } /* - Item is an entry in a Collection that contains a Secret. + Item is an entry in a Collection that contains a Secret. Do not change any of these values directly; use the associated methods instead. https://developer-old.gnome.org/libsecret/0.18/SecretItem.html https://specifications.freedesktop.org/secret-service/latest/re03.html */ @@ -107,8 +121,18 @@ type Item struct { *DbusObject // Secret is the corresponding Secret object. Secret *Secret `json:"secret"` - // lastModified is unexported because it's important that API users don't change it; it's used by Collection.Modified. - lastModified time.Time + // IsLocked indicates if the Item is locked or not. Status updated by Item.Locked. + IsLocked bool + // Attrs are the Item's attributes (as would be returned via Item.Attributes). + Attrs map[string]string `json:"attributes"` + // LabelName is the Item's label (as given by Item.Label and modified by Item.Relabel). + LabelName string `json:"label"` + // SecretType is the Item's secret type (as returned by Item.Type). + SecretType string `json:"type"` + // CreatedAt is when this Item was created (used by Item.Created). + CreatedAt time.Time `json:"created"` + // LastModified is when this Item was last changed; it's used by Item.Modified. + LastModified time.Time `json:"modified"` // lastModifiedSet is unexported; it's only used to determine if this is a first-initialization of the modification time or not. lastModifiedSet bool /*