droboticflow/internal/store/object_sync_auth.go

138 lines
5.7 KiB
Go

package store
import (
"context"
"errors"
"time"
"droboticflow/internal/domain"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var ErrObjectSyncCredentialChanged = errors.New("credential changed, revoked or activation expired")
func pendingBindingLive(binding domain.ObjectSyncCredentialTokenBinding, now time.Time) bool {
if !binding.Pending {
return true
}
expiry, err := time.Parse(time.RFC3339Nano, binding.ExpiresAt)
return err == nil && expiry.After(now)
}
func (s *MemoryStore) AddObjectSyncPendingToken(_ context.Context, id, secretHash string, binding domain.ObjectSyncCredentialTokenBinding) error {
s.mu.Lock()
defer s.mu.Unlock()
current, ok := s.objectSyncCredentials[id]
if !ok || !current.Enabled || current.SecretHash != secretHash {
return ErrObjectSyncCredentialChanged
}
kept := make([]domain.ObjectSyncCredentialTokenBinding, 0, len(current.TokenBindings)+1)
for _, old := range current.TokenBindings {
if !old.Pending || (old.DeviceID != binding.DeviceID && pendingBindingLive(old, time.Now())) {
kept = append(kept, old)
}
}
current.TokenBindings = append(kept, binding)
current.UpdatedAt = nowISO()
s.objectSyncCredentials[id] = current
return nil
}
func (s *MongoStore) AddObjectSyncPendingToken(ctx context.Context, id, secretHash string, binding domain.ObjectSyncCredentialTokenBinding) error {
kept := bson.M{"$filter": bson.M{"input": bson.M{"$ifNull": bson.A{"$tokenBindings", bson.A{}}}, "as": "b", "cond": bson.M{"$or": bson.A{
bson.M{"$ne": bson.A{"$$b.pending", true}}, bson.M{"$and": bson.A{bson.M{"$ne": bson.A{"$$b.deviceId", binding.DeviceID}}, bson.M{"$gt": bson.A{"$$b.expiresAt", nowISO()}}}},
}}}}
result, err := s.objectSyncCredentials.UpdateOne(ctx, bson.M{"id": id, "enabled": true, "secretHash": secretHash}, mongo.Pipeline{{{Key: "$set", Value: bson.M{"tokenBindings": bson.M{"$concatArrays": bson.A{kept, bson.M{"$literal": []domain.ObjectSyncCredentialTokenBinding{binding}}}}, "updatedAt": nowISO()}}}})
if err != nil {
return err
}
if result.MatchedCount != 1 {
return ErrObjectSyncCredentialChanged
}
return nil
}
func (s *MemoryStore) ActivateObjectSyncToken(_ context.Context, id, deviceID, hash, activationID string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
current, ok := s.objectSyncCredentials[id]
if !ok || !current.Enabled {
return false, nil
}
var selected *domain.ObjectSyncCredentialTokenBinding
for _, b := range current.TokenBindings {
if b.TokenHash == hash && b.DeviceID == deviceID && b.ActivationID == activationID && pendingBindingLive(b, time.Now()) {
copy := b
selected = &copy
break
}
}
if selected == nil {
return false, nil
}
if !selected.Pending {
return true, nil
} // A replay must not erase a later pending token.
selected.Pending = false
selected.ExpiresAt = ""
kept := make([]domain.ObjectSyncCredentialTokenBinding, 0, len(current.TokenBindings))
for _, b := range current.TokenBindings {
if b.DeviceID != deviceID {
kept = append(kept, b)
}
}
current.TokenBindings = append(kept, *selected)
current.UpdatedAt = nowISO()
s.objectSyncCredentials[id] = current
return true, nil
}
func (s *MongoStore) ActivateObjectSyncToken(ctx context.Context, id, deviceID, hash, activationID string) (bool, error) {
now := nowISO()
filter := bson.M{"id": id, "enabled": true, "tokenBindings": bson.M{"$elemMatch": bson.M{"tokenHash": hash, "deviceId": deviceID, "activationId": activationID, "pending": true, "expiresAt": bson.M{"$gt": now}}}}
kept := bson.M{"$filter": bson.M{"input": "$tokenBindings", "as": "b", "cond": bson.M{"$ne": bson.A{"$$b.deviceId", deviceID}}}}
active := domain.ObjectSyncCredentialTokenBinding{TokenHash: hash, DeviceID: deviceID, ActivationID: activationID, CreatedAt: now}
result, err := s.objectSyncCredentials.UpdateOne(ctx, filter, mongo.Pipeline{{{Key: "$set", Value: bson.M{"tokenBindings": bson.M{"$concatArrays": bson.A{kept, bson.M{"$literal": []domain.ObjectSyncCredentialTokenBinding{active}}}}, "updatedAt": now}}}})
if err != nil {
return false, err
}
if result.MatchedCount == 1 {
return true, nil
}
// Already activated is a no-op, not a second rotation: a later pending
// authentication for the same device must survive this delayed replay.
existing, err := s.objectSyncCredentials.CountDocuments(ctx, bson.M{"id": id, "enabled": true, "tokenBindings": bson.M{"$elemMatch": bson.M{"deviceId": deviceID, "tokenHash": hash, "activationId": activationID, "pending": bson.M{"$ne": true}}}}, options.Count().SetLimit(1))
return existing == 1, err
}
func (s *MemoryStore) TouchObjectSyncCredential(_ context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
v, ok := s.objectSyncCredentials[id]
if ok {
v.LastUsedAt = nowISO()
s.objectSyncCredentials[id] = v
}
return nil
}
func (s *MongoStore) TouchObjectSyncCredential(ctx context.Context, id string) error {
_, err := s.objectSyncCredentials.UpdateOne(ctx, bson.M{"id": id}, bson.M{"$set": bson.M{"lastUsedAt": nowISO()}})
return err
}
// A device ID cannot be re-owned during concurrent registrations.
func (s *MemoryStore) RegisterObjectSyncDevice(_ context.Context, device domain.ObjectSyncDeviceRecord) error {
s.mu.Lock()
defer s.mu.Unlock()
old, ok := s.objectSyncDevices[device.ID]
if ok && old.OrganizationID != device.OrganizationID {
return ErrObjectSyncCredentialChanged
}
s.objectSyncDevices[device.ID] = device
return nil
}
func (s *MongoStore) RegisterObjectSyncDevice(ctx context.Context, device domain.ObjectSyncDeviceRecord) error {
_, err := s.objectSyncDevices.ReplaceOne(ctx, bson.M{"id": device.ID, "organizationId": device.OrganizationID}, device, options.Replace().SetUpsert(true))
if mongo.IsDuplicateKeyError(err) {
return ErrObjectSyncCredentialChanged
}
return err
}