Add private CardDAV synchronization and contact revision recovery
This commit is contained in:
1 parent
433169c7e7
commit
19e12f96a8
32 files changed
+1855
-47
No files matched your search
@@ -0,0 +1,284 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrContactUIDConflict = errors.New("contact UID conflict")
|
||||
var ErrContactSyncToken = errors.New("invalid contact sync token")
|
||||
|
||||
func ContactPropertyValues(c Contact, key string) []string {
|
||||
lines, err := cardLines(c.VCard)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
values := []string{}
|
||||
for _, line := range lines[1 : len(lines)-1] {
|
||||
k, v, e := cardKey(line)
|
||||
if e == nil && k == strings.ToUpper(key) {
|
||||
values = append(values, cardText(v))
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func ValidContactDAVName(name string) bool {
|
||||
if len(name) < 5 || len(name) > 128 || !strings.HasSuffix(name, ".vcf") || strings.HasPrefix(name, ".") {
|
||||
return false
|
||||
}
|
||||
for _, c := range name {
|
||||
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("-_.", c)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func ContactETag(c Contact) string { return fmt.Sprintf(`"%d"`, c.Version) }
|
||||
|
||||
type ContactDAVItem struct {
|
||||
Contact
|
||||
Name string
|
||||
Sequence int64
|
||||
Size int
|
||||
}
|
||||
type ContactDAVSnapshot struct {
|
||||
Items []ContactDAVItem
|
||||
Token string
|
||||
More bool
|
||||
}
|
||||
|
||||
// Scope and epoch bind opaque tokens to this database, domain and owner. Each
|
||||
// resource retains only its latest sequence; soft-deleted rows are tombstones.
|
||||
func (s *Store) ContactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int) (ContactDAVSnapshot, error) {
|
||||
if limit < 0 || limit > 200 {
|
||||
return ContactDAVSnapshot{}, ErrTaskInvalid
|
||||
}
|
||||
return s.contactDAVSnapshot(ctx, domain, actor, token, limit, false)
|
||||
}
|
||||
|
||||
// PROPFIND inventories contain metadata only, never thousands of vCard bodies.
|
||||
// The same read transaction supplies both the inventory and its change token.
|
||||
func (s *Store) ContactDAVInventory(ctx context.Context, domain, actor string) (ContactDAVSnapshot, error) {
|
||||
return s.contactDAVSnapshot(ctx, domain, actor, "", 5000, true)
|
||||
}
|
||||
|
||||
func (s *Store) contactDAVSnapshot(ctx context.Context, domain, actor, token string, limit int, metadata bool) (ContactDAVSnapshot, error) {
|
||||
out := ContactDAVSnapshot{Items: []ContactDAVItem{}}
|
||||
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if err = taskActor(ctx, tx, domain, actor, false); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||
return out, err
|
||||
}
|
||||
var epoch string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT value FROM organizer_contact_epoch WHERE id=1`).Scan(&epoch); err != nil {
|
||||
return out, err
|
||||
}
|
||||
hash := sha256.Sum256([]byte(epoch + "\x00" + domain + "\x00" + actor))
|
||||
prefix := "urn:pageswiki:contacts:" + hex.EncodeToString(hash[:]) + ":"
|
||||
var high int64
|
||||
if err = tx.QueryRowContext(ctx, `SELECT COALESCE(MAX(sequence),0) FROM organizer_contact_changes WHERE domain_uuid=? AND owner_uuid=?`, domain, actor).Scan(&high); err != nil {
|
||||
return out, err
|
||||
}
|
||||
since := int64(0)
|
||||
if token != "" {
|
||||
if !strings.HasPrefix(token, prefix) {
|
||||
return out, ErrContactSyncToken
|
||||
}
|
||||
since, err = strconv.ParseInt(strings.TrimPrefix(token, prefix), 10, 64)
|
||||
if err != nil || since < 0 || since > high || prefix+strconv.FormatInt(since, 10) != token {
|
||||
return out, ErrContactSyncToken
|
||||
}
|
||||
}
|
||||
out.Token = prefix + strconv.FormatInt(high, 10)
|
||||
if limit == 0 {
|
||||
return out, nil
|
||||
}
|
||||
fields := `c.data,n.name,x.sequence,0`
|
||||
if metadata {
|
||||
fields = `json_object('uuid',c.uuid,'version',c.version),n.name,x.sequence,length(CAST(json_extract(c.data,'$.vcard') AS BLOB))`
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `SELECT `+fields+` FROM organizer_contact_changes x JOIN organizer_contacts c USING(domain_uuid,owner_uuid,uuid) JOIN organizer_contact_names n USING(domain_uuid,owner_uuid,uuid) WHERE x.domain_uuid=? AND x.owner_uuid=? AND x.sequence>? AND (?<>'' OR c.deleted=0) ORDER BY x.sequence LIMIT ?`, domain, actor, since, token, limit+1)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
if len(out.Items) == limit {
|
||||
out.More = true
|
||||
out.Token = prefix + strconv.FormatInt(out.Items[len(out.Items)-1].Sequence, 10)
|
||||
break
|
||||
}
|
||||
var item ContactDAVItem
|
||||
var raw string
|
||||
if err = rows.Scan(&raw, &item.Name, &item.Sequence, &item.Size); err != nil {
|
||||
return out, err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &item.Contact); err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Items = append(out.Items, item)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ContactDAVResource(ctx context.Context, domain, actor, name string) (Contact, error) {
|
||||
if !ValidContactDAVName(name) {
|
||||
return Contact{}, ErrTaskInvalid
|
||||
}
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
var id string
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&id)
|
||||
if err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
return s.Contact(ctx, domain, actor, id)
|
||||
}
|
||||
|
||||
// The version is compared under the same write lock as credential revocation,
|
||||
// membership and extension state. No read-modify-write bypass for DAV clients.
|
||||
func (s *Store) SaveContactDAV(ctx context.Context, domain, actor, credential, name, raw string, version int64, remove bool) (Contact, error) {
|
||||
if !ValidContactDAVName(name) {
|
||||
return Contact{}, ErrTaskInvalid
|
||||
}
|
||||
old, err := s.ContactDAVResource(ctx, domain, actor, name)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return old, err
|
||||
}
|
||||
if old.Version != version {
|
||||
return old, ErrTaskConflict
|
||||
}
|
||||
if remove {
|
||||
if old.Version == 0 || old.Deleted {
|
||||
return old, sql.ErrNoRows
|
||||
}
|
||||
old.Deleted = true
|
||||
return s.saveContact(ctx, domain, actor, old, "fields", credential, name)
|
||||
}
|
||||
id := old.UUID
|
||||
if id == "" {
|
||||
id = strings.TrimSuffix(name, ".vcf")
|
||||
if u, e := uuid.Parse(id); e != nil || u.String() != id {
|
||||
id = uuid.NewSHA1(uuid.NameSpaceURL, []byte(domain+"\x00"+actor+"\x00"+name)).String()
|
||||
}
|
||||
}
|
||||
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", credential, name)
|
||||
}
|
||||
|
||||
type ContactRevision struct {
|
||||
Version int64 `json:"version"`
|
||||
Deleted bool `json:"deleted"`
|
||||
CreatedMS int64 `json:"created_ms"`
|
||||
}
|
||||
|
||||
func (s *Store) ContactHistory(ctx context.Context, domain, actor, id string, before int64) ([]ContactRevision, error) {
|
||||
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT version,deleted,created_ms FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND (?=0 OR version<?) ORDER BY version DESC LIMIT 100`, domain, actor, id, before, before)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []ContactRevision{}
|
||||
for rows.Next() {
|
||||
var r ContactRevision
|
||||
if err = rows.Scan(&r.Version, &r.Deleted, &r.CreatedMS); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (s *Store) RestoreContactRevision(ctx context.Context, domain, actor, id string, revision, version int64) (Contact, error) {
|
||||
old, err := s.Contact(ctx, domain, actor, id)
|
||||
if err != nil {
|
||||
return old, err
|
||||
}
|
||||
if old.Version != version {
|
||||
return old, ErrTaskConflict
|
||||
}
|
||||
var hash string
|
||||
if err = s.DB.QueryRowContext(ctx, `SELECT hash FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, revision).Scan(&hash); err != nil {
|
||||
return old, err
|
||||
}
|
||||
raw, err := s.readDocument(hash)
|
||||
if err != nil {
|
||||
return old, err
|
||||
}
|
||||
return s.saveContact(ctx, domain, actor, Contact{UUID: id, Version: version, VCard: raw}, "dav", "", "")
|
||||
}
|
||||
|
||||
func (s *Store) ContactAtRevision(ctx context.Context, domain, actor, id string, version int64) (Contact, error) {
|
||||
if _, err := s.Contact(ctx, domain, actor, id); err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
var hash string
|
||||
var deleted bool
|
||||
if err := s.DB.QueryRowContext(ctx, `SELECT hash,deleted FROM organizer_contact_revisions WHERE domain_uuid=? AND owner_uuid=? AND uuid=? AND version=?`, domain, actor, id, version).Scan(&hash, &deleted); err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
raw, err := s.readDocument(hash)
|
||||
if err != nil {
|
||||
return Contact{}, err
|
||||
}
|
||||
c, err := ParseContact(raw)
|
||||
c.UUID = id
|
||||
c.Version = version
|
||||
c.Deleted = deleted
|
||||
return c, err
|
||||
}
|
||||
|
||||
// One SQLite read snapshot, bounded before headers are sent. An export must
|
||||
// never look successful when contacts have been silently truncated.
|
||||
func (s *Store) ExportContacts(ctx context.Context, domain, actor string) (string, error) {
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := contactEnabled(ctx, s.DB, domain); err != nil {
|
||||
return "", err
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND deleted=0 ORDER BY uuid LIMIT 5001`, domain, actor)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out strings.Builder
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var c Contact
|
||||
if err = rows.Scan(&raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = json.Unmarshal([]byte(raw), &c); err != nil {
|
||||
return "", err
|
||||
}
|
||||
count++
|
||||
if count > 5000 || out.Len()+len(c.VCard) > 16<<20 {
|
||||
return "", ErrTaskDAVLimit
|
||||
}
|
||||
out.WriteString(c.VCard)
|
||||
}
|
||||
return out.String(), rows.Err()
|
||||
}
|
||||
@@ -21,7 +21,29 @@ var contactMigrations = []db.SQLMigration{{Version: 1, Name: "private_address_bo
|
||||
`CREATE TABLE organizer_contacts(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,uid TEXT NOT NULL,version INTEGER NOT NULL,name TEXT NOT NULL,search TEXT NOT NULL,data TEXT NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,uid))`,
|
||||
`CREATE INDEX organizer_contacts_owner ON organizer_contacts(domain_uuid,owner_uuid,deleted,uuid)`,
|
||||
`CREATE TABLE organizer_contact_revisions(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,version INTEGER NOT NULL,hash TEXT NOT NULL,deleted INTEGER NOT NULL,created_ms INTEGER NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid,version))`,
|
||||
}, Assertions: []string{schemaColumns("organizer_contacts", "domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted"), schemaUnique("organizer_contacts", "domain_uuid,owner_uuid,uid")}}}
|
||||
}, Assertions: []string{schemaColumns("organizer_contacts", "domain_uuid,owner_uuid,uuid,uid,version,name,search,data,hash,deleted"), schemaUnique("organizer_contacts", "domain_uuid,owner_uuid,uid")}}, {Version: 2, Name: "contact_dav_sync", Statements: []string{
|
||||
`CREATE TABLE organizer_contact_credentials(credential_id TEXT PRIMARY KEY)`,
|
||||
`CREATE TRIGGER organizer_contact_credential_delete AFTER DELETE ON organizer_dav_credentials BEGIN DELETE FROM organizer_contact_credentials WHERE credential_id=old.id; END`,
|
||||
`CREATE TABLE organizer_contact_names(domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,name TEXT NOT NULL,PRIMARY KEY(domain_uuid,owner_uuid,uuid),UNIQUE(domain_uuid,owner_uuid,name))`,
|
||||
`INSERT INTO organizer_contact_names SELECT domain_uuid,owner_uuid,uuid,uuid||'.vcf' FROM organizer_contacts`,
|
||||
`CREATE TABLE organizer_contact_epoch(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL)`,
|
||||
`INSERT INTO organizer_contact_epoch VALUES(1,lower(hex(randomblob(32))))`,
|
||||
`CREATE TABLE organizer_contact_changes(sequence INTEGER PRIMARY KEY AUTOINCREMENT,domain_uuid TEXT NOT NULL,owner_uuid TEXT NOT NULL,uuid TEXT NOT NULL,UNIQUE(domain_uuid,owner_uuid,uuid))`,
|
||||
`CREATE INDEX organizer_contact_changes_owner ON organizer_contact_changes(domain_uuid,owner_uuid,sequence,uuid)`,
|
||||
`INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) SELECT domain_uuid,owner_uuid,uuid FROM organizer_contacts ORDER BY domain_uuid,owner_uuid,uuid`,
|
||||
`CREATE TRIGGER organizer_contact_insert AFTER INSERT ON organizer_contacts BEGIN INSERT INTO organizer_contact_names SELECT new.domain_uuid,new.owner_uuid,new.uuid,new.uuid||'.vcf' WHERE NOT EXISTS(SELECT 1 FROM organizer_contact_names WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid); INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||
`CREATE TRIGGER organizer_contact_update AFTER UPDATE ON organizer_contacts BEGIN DELETE FROM organizer_contact_changes WHERE domain_uuid=new.domain_uuid AND owner_uuid=new.owner_uuid AND uuid=new.uuid; INSERT INTO organizer_contact_changes(domain_uuid,owner_uuid,uuid) VALUES(new.domain_uuid,new.owner_uuid,new.uuid); END`,
|
||||
}, Assertions: []string{
|
||||
schemaColumns("organizer_contact_changes", "sequence,domain_uuid,owner_uuid,uuid"),
|
||||
schemaColumns("organizer_contact_credentials", "credential_id"),
|
||||
schemaColumns("organizer_contact_epoch", "id,value"),
|
||||
schemaColumns("organizer_contact_names", "domain_uuid,owner_uuid,uuid,name"),
|
||||
schemaUnique("organizer_contact_names", "domain_uuid,owner_uuid,name"),
|
||||
schemaUnique("organizer_contact_changes", "domain_uuid,owner_uuid,uuid"),
|
||||
schemaIndex("organizer_contact_changes", "organizer_contact_changes_owner", "domain_uuid,owner_uuid,sequence,uuid"),
|
||||
`SELECT 1 WHERE (SELECT count(*) FROM organizer_contact_epoch WHERE id=1 AND length(value)=64)<>1`,
|
||||
`SELECT 1 WHERE (SELECT count(*) FROM sqlite_master WHERE type='trigger' AND name IN ('organizer_contact_insert','organizer_contact_update','organizer_contact_credential_delete'))<>3`,
|
||||
}}}
|
||||
|
||||
type Contact struct {
|
||||
UUID string `json:"uuid"`
|
||||
@@ -344,6 +366,13 @@ func (s *Store) Contact(ctx context.Context, domain, actor, id string) (Contact,
|
||||
return c, err
|
||||
}
|
||||
func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact, rawImport bool) (Contact, error) {
|
||||
mode := "fields"
|
||||
if rawImport {
|
||||
mode = "import"
|
||||
}
|
||||
return s.saveContact(ctx, domain, actor, c, mode, "", "")
|
||||
}
|
||||
func (s *Store) saveContact(ctx context.Context, domain, actor string, c Contact, mode, credential, name string) (Contact, error) {
|
||||
if s.ReadOnly {
|
||||
return c, ErrReadOnly
|
||||
}
|
||||
@@ -364,6 +393,11 @@ func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact
|
||||
if err = contactEnabled(ctx, tx, domain); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if credential != "" {
|
||||
if err = davCredentialAllowed(ctx, tx, domain, actor, credential, true, "contacts"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
var old Contact
|
||||
var data string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&data)
|
||||
@@ -377,8 +411,8 @@ func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact
|
||||
if c.Version != old.Version {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
if rawImport {
|
||||
if c.Version != 0 {
|
||||
if mode == "import" || mode == "dav" {
|
||||
if mode == "import" && c.Version != 0 {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
parsed, e := ParseContact(c.VCard)
|
||||
@@ -386,7 +420,11 @@ func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact
|
||||
return c, e
|
||||
}
|
||||
parsed.UUID = c.UUID
|
||||
parsed.Version = c.Version
|
||||
c = parsed
|
||||
if old.Version != 0 && old.UID != c.UID {
|
||||
return c, ErrContactUIDConflict
|
||||
}
|
||||
var existing string
|
||||
err = tx.QueryRowContext(ctx, `SELECT data FROM organizer_contacts WHERE domain_uuid=? AND owner_uuid=? AND uid=?`, domain, actor, c.UID).Scan(&existing)
|
||||
if err == nil {
|
||||
@@ -394,12 +432,17 @@ func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact
|
||||
if json.Unmarshal([]byte(existing), &previous) != nil {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
if previous.VCard != c.VCard || previous.Deleted {
|
||||
return c, ErrTaskConflict
|
||||
if mode == "import" {
|
||||
if previous.VCard != c.VCard || previous.Deleted {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
return previous, nil
|
||||
}
|
||||
if previous.UUID != c.UUID {
|
||||
return c, ErrContactUIDConflict
|
||||
}
|
||||
return previous, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return c, err
|
||||
}
|
||||
} else {
|
||||
@@ -408,6 +451,29 @@ func (s *Store) SaveContact(ctx context.Context, domain, actor string, c Contact
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
if name != "" {
|
||||
if !ValidContactDAVName(name) {
|
||||
return c, ErrTaskInvalid
|
||||
}
|
||||
var existing string
|
||||
err = tx.QueryRowContext(ctx, `SELECT name FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND uuid=?`, domain, actor, c.UUID).Scan(&existing)
|
||||
if err == nil && existing != name {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return c, err
|
||||
}
|
||||
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO organizer_contact_names VALUES(?,?,?,?)`, domain, actor, c.UUID, name); err != nil {
|
||||
return c, err
|
||||
}
|
||||
var mapped string
|
||||
if err = tx.QueryRowContext(ctx, `SELECT uuid FROM organizer_contact_names WHERE domain_uuid=? AND owner_uuid=? AND name=?`, domain, actor, name).Scan(&mapped); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if mapped != c.UUID {
|
||||
return c, ErrTaskConflict
|
||||
}
|
||||
}
|
||||
c.Version++
|
||||
b, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
@@ -8,6 +9,48 @@ import (
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
func TestContactDAVUpgradePreservesRowsAndTracksChanges(t *testing.T) {
|
||||
st := newSchemaTestStore(t)
|
||||
ctx := context.Background()
|
||||
if e := db.ApplySQLiteMigrations(ctx, st.DB, "contacts", contactMigrations[:1]); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := st.DB.Exec(`INSERT INTO organizer_contacts VALUES('d','u','c','uid',1,'Name','name','{"name":"Name"}','hash',0)`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for range 2 {
|
||||
if e := st.ensureSchemaComponent("contacts"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
var name, data string
|
||||
var before, after int64
|
||||
var count int
|
||||
if e := st.DB.QueryRow(`SELECT name FROM organizer_contact_names WHERE uuid='c'`).Scan(&name); e != nil || name != "c.vcf" {
|
||||
t.Fatal(name, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT data FROM organizer_contacts WHERE uuid='c'`).Scan(&data); e != nil || data != `{"name":"Name"}` {
|
||||
t.Fatal(data, e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT sequence FROM organizer_contact_changes WHERE uuid='c'`).Scan(&before); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for range 3 {
|
||||
if _, e := st.DB.Exec(`UPDATE organizer_contacts SET deleted=1 WHERE uuid='c'`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT count(*),max(sequence) FROM organizer_contact_changes WHERE uuid='c'`).Scan(&count, &after); e != nil || count != 1 || after <= before {
|
||||
t.Fatal(count, before, after, e)
|
||||
}
|
||||
if _, e := st.DB.Exec(`INSERT INTO organizer_dav_credentials VALUES('credential'); INSERT INTO organizer_contact_credentials VALUES('credential'); DELETE FROM organizer_dav_credentials WHERE id='credential'`); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := st.DB.QueryRow(`SELECT count(*) FROM organizer_contact_credentials`).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal(count, e)
|
||||
}
|
||||
}
|
||||
|
||||
func newSchemaTestStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
database, err := db.Open(filepath.Join(t.TempDir(), "schema.db"))
|
||||
@@ -20,6 +63,9 @@ func newSchemaTestStore(t *testing.T) *Store {
|
||||
if _, err = database.Exec(`CREATE TABLE organizer_items(domain_uuid TEXT,owner_uuid TEXT,uuid TEXT,kind TEXT,data TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = database.Exec(`CREATE TABLE organizer_dav_credentials(id TEXT PRIMARY KEY)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &Store{DB: database}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,10 @@ func (s *Store) CreateTaskDAVCredential(ctx context.Context, domain, actor, labe
|
||||
|
||||
func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label string, write bool, days int, scope string, compatibility ...bool) (TaskDAVCredential, string, error) {
|
||||
compat := len(compatibility) == 1 && compatibility[0]
|
||||
if scope != "tasks" && scope != "calendar" && scope != "all" {
|
||||
if scope == "contacts" && compat {
|
||||
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||
}
|
||||
if scope != "tasks" && scope != "calendar" && scope != "all" && scope != "contacts" {
|
||||
return TaskDAVCredential{}, "", ErrTaskInvalid
|
||||
}
|
||||
label = strings.TrimSpace(label)
|
||||
@@ -71,12 +74,19 @@ func (s *Store) CreateDAVCredential(ctx context.Context, domain, actor, label st
|
||||
// of accidentally interpreting them as task-only authority.
|
||||
secret = "pw_dav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
if scope == "contacts" {
|
||||
secret = "pw_contactdav_" + base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
now := time.Now()
|
||||
c := TaskDAVCredential{ID: uuid.NewString(), Label: label, Write: write, CreatedMS: now.UnixMilli(), ExpiresMS: now.Add(time.Duration(days) * 24 * time.Hour).UnixMilli(), Scope: scope}
|
||||
c.CalendarAccessCompat = compat
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_credentials(id,domain_uuid,owner_uuid,label,secret_hash,write_access,created_ms,expires_ms) VALUES(?,?,?,?,?,?,?,?)`, c.ID, domain, actor, c.Label, taskDAVSecretHash(secret), write, c.CreatedMS, c.ExpiresMS)
|
||||
if err == nil {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
||||
if scope == "contacts" {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_contact_credentials VALUES(?)`, c.ID)
|
||||
} else {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_scopes(credential_id,scope) VALUES(?,?)`, c.ID, scope)
|
||||
}
|
||||
}
|
||||
if err == nil && compat {
|
||||
_, err = tx.ExecContext(ctx, `INSERT INTO organizer_dav_compat(credential_id) VALUES(?)`, c.ID)
|
||||
@@ -90,7 +100,7 @@ func (s *Store) ListTaskDAVCredentials(ctx context.Context, domain, actor string
|
||||
if err := taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks'),EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
||||
rows, err := s.DB.QueryContext(ctx, `SELECT id,label,write_access,created_ms,expires_ms,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) THEN 'contacts' ELSE COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') END,EXISTS(SELECT 1 FROM organizer_dav_compat WHERE credential_id=id) FROM organizer_dav_credentials WHERE domain_uuid=? AND owner_uuid=? ORDER BY created_ms DESC LIMIT 100`, domain, actor)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -130,7 +140,7 @@ func davCredentialAllowed(ctx context.Context, q interface {
|
||||
QueryRowContext(context.Context, string, ...any) *sql.Row
|
||||
}, domain, actor, id string, write bool, scope string) error {
|
||||
var yes bool
|
||||
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))`, id, domain, actor, time.Now().UnixMilli(), write, scope).Scan(&yes); err != nil {
|
||||
if err := q.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM organizer_dav_credentials WHERE id=? AND domain_uuid=? AND owner_uuid=? AND expires_ms>? AND (?=0 OR write_access=1) AND ((?='contacts' AND EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id)) OR (? IN ('tasks','calendar') AND NOT EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=id) AND COALESCE((SELECT scope FROM organizer_dav_scopes WHERE credential_id=id),'tasks') IN (?, 'all'))))`, id, domain, actor, time.Now().UnixMilli(), write, scope, scope, scope).Scan(&yes); err != nil {
|
||||
return err
|
||||
}
|
||||
if !yes {
|
||||
@@ -151,16 +161,19 @@ func (s *Store) CheckDAVCredential(ctx context.Context, domain, actor, id string
|
||||
|
||||
// An empty requested scope is discovery only; callers must filter collections.
|
||||
func (s *Store) AuthenticateDAV(ctx context.Context, domain, id, secret, requested string) (string, bool, string, error) {
|
||||
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_")) {
|
||||
if len(secret) > 128 || !(strings.HasPrefix(secret, "pw_taskdav_") || strings.HasPrefix(secret, "pw_dav_") || strings.HasPrefix(secret, "pw_contactdav_")) {
|
||||
return "", false, "", ErrAccessDenied
|
||||
}
|
||||
var actor, hash, state, scope string
|
||||
var write bool
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,COALESCE(s.scope,'tasks') FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
||||
err := s.DB.QueryRowContext(ctx, `SELECT c.owner_uuid,c.secret_hash,c.write_access,p.state,CASE WHEN EXISTS(SELECT 1 FROM organizer_contact_credentials WHERE credential_id=c.id) THEN 'contacts' ELSE COALESCE(s.scope,'tasks') END FROM organizer_dav_credentials c JOIN principals p ON p.uuid=c.owner_uuid LEFT JOIN organizer_dav_scopes s ON s.credential_id=c.id WHERE c.id=? AND c.domain_uuid=? AND c.expires_ms>?`, id, domain, time.Now().UnixMilli()).Scan(&actor, &hash, &write, &state, &scope)
|
||||
if err != nil || subtle.ConstantTimeCompare([]byte(hash), []byte(taskDAVSecretHash(secret))) != 1 {
|
||||
return "", false, "", ErrAccessDenied
|
||||
}
|
||||
if requested != "" && scope != "all" && scope != requested {
|
||||
if strings.HasPrefix(secret, "pw_contactdav_") && scope != "contacts" {
|
||||
return "", false, "", ErrAccessDenied
|
||||
}
|
||||
if requested != "" && scope != requested && !(scope == "all" && (requested == "tasks" || requested == "calendar")) {
|
||||
return "", false, "", ErrAccessDenied
|
||||
}
|
||||
if err = taskActor(ctx, s.DB, domain, actor, false); err != nil {
|
||||
|
||||
Reference in new issue
Block a user