feat: add safe multi-account routing and prepare public release
This commit is contained in:
71 files changed
+2906
-120
No files matched your search
+157
-55
@@ -91,14 +91,15 @@ type DNSBatchResult struct {
|
||||
type plannedDNSBatch struct {
|
||||
plan DNSBatchPlan
|
||||
zone domain.Zone
|
||||
cloud provider.CloudProvider
|
||||
cloud provider.Provider
|
||||
batch provider.DNSBatchService
|
||||
auth provider.Auth
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
repo store.Repository
|
||||
secrets store.SecretStore
|
||||
providers map[string]provider.CloudProvider
|
||||
providers map[string]provider.Provider
|
||||
now func() time.Time
|
||||
events chan Event
|
||||
healthCheck func(context.Context) error
|
||||
@@ -107,17 +108,22 @@ type Service struct {
|
||||
recoveryBlocked atomic.Bool
|
||||
}
|
||||
|
||||
var (
|
||||
_ provider.DNS01Solver = (*Service)(nil)
|
||||
_ provider.DNS01Reconciler = (*Service)(nil)
|
||||
)
|
||||
|
||||
func New(repo store.Repository, secrets store.SecretStore) *Service {
|
||||
return &Service{
|
||||
repo: repo,
|
||||
secrets: secrets,
|
||||
providers: make(map[string]provider.CloudProvider),
|
||||
providers: make(map[string]provider.Provider),
|
||||
now: time.Now,
|
||||
events: make(chan Event, 128),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) RegisterProvider(name string, value provider.CloudProvider) {
|
||||
func (s *Service) RegisterProvider(name string, value provider.Provider) {
|
||||
s.providers[name] = value
|
||||
}
|
||||
|
||||
@@ -177,6 +183,50 @@ func (s *Service) ResolveCredential(ctx context.Context, credentialID string) (p
|
||||
return s.auth(ctx, credential)
|
||||
}
|
||||
|
||||
// PresentDNS01, CleanupDNS01, and ReconcileDNS01 make Service the provider
|
||||
// router used by the ACME engine and crash recovery. Routing is based only on
|
||||
// the provider identity bound into Auth; remote zone IDs are not globally
|
||||
// unique and must never select a provider implicitly.
|
||||
func (s *Service) PresentDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, value, jobID string) (string, error) {
|
||||
p, err := s.dns01Provider(auth)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return p.PresentDNS01(ctx, auth, zoneID, fqdn, value, jobID)
|
||||
}
|
||||
|
||||
func (s *Service) CleanupDNS01(ctx context.Context, auth provider.Auth, zoneID, recordID string) error {
|
||||
p, err := s.dns01Provider(auth)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.CleanupDNS01(ctx, auth, zoneID, recordID)
|
||||
}
|
||||
|
||||
func (s *Service) ReconcileDNS01(ctx context.Context, auth provider.Auth, zoneID, fqdn, valueHash, jobID string) (string, bool, error) {
|
||||
p, err := s.dns01Provider(auth)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
reconciler, ok := p.(provider.DNS01Reconciler)
|
||||
if !ok {
|
||||
return "", false, provider.Unsupported(auth.Provider, "DNS-01 reconciliation")
|
||||
}
|
||||
return reconciler.ReconcileDNS01(ctx, auth, zoneID, fqdn, valueHash, jobID)
|
||||
}
|
||||
|
||||
func (s *Service) dns01Provider(auth provider.Auth) (provider.Provider, error) {
|
||||
providerName := strings.TrimSpace(auth.Provider)
|
||||
if providerName == "" {
|
||||
return nil, errors.New("DNS-01 credential has no provider identity")
|
||||
}
|
||||
p, ok := s.providers[providerName]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("DNS-01 provider %q is not registered", providerName)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (s *Service) IssueCertificates(ctx context.Context, request IssueZonesRequest) (IssueZonesResult, error) {
|
||||
if err := s.ensureRecoveryReady(ctx); err != nil {
|
||||
return IssueZonesResult{}, err
|
||||
@@ -341,7 +391,7 @@ func (s *Service) AddCloudflareCredential(ctx context.Context, input AddCredenti
|
||||
}
|
||||
|
||||
id := identifier.New("cred")
|
||||
auth := provider.Auth{CredentialID: id, Token: strings.TrimSpace(input.Token), Kind: input.Kind, AccountID: strings.TrimSpace(input.AccountID)}
|
||||
auth := provider.Auth{Provider: domain.ProviderCloudflare, CredentialID: id, Token: strings.TrimSpace(input.Token), Kind: input.Kind, AccountID: strings.TrimSpace(input.AccountID)}
|
||||
verification, err := p.VerifyCredential(ctx, auth)
|
||||
if err != nil {
|
||||
return domain.Credential{}, fmt.Errorf("verify Cloudflare credential: %w", err)
|
||||
@@ -393,7 +443,7 @@ func (s *Service) AddCloudflareCredential(ctx context.Context, input AddCredenti
|
||||
if len(verification.Accounts) > 0 {
|
||||
links := make([]domain.AccountCredential, 0, len(verification.Accounts))
|
||||
for i := range verification.Accounts {
|
||||
normalizeAccount(&verification.Accounts[i])
|
||||
normalizeAccount(&verification.Accounts[i], domain.ProviderCloudflare)
|
||||
_, known := knownAccounts[verification.Accounts[i].ID]
|
||||
links = append(links, domain.AccountCredential{AccountID: verification.Accounts[i].ID, CredentialID: id, Preferred: !known})
|
||||
}
|
||||
@@ -567,7 +617,7 @@ func compensateSecretDelete(ctx context.Context, secrets store.SecretStore, refe
|
||||
}
|
||||
|
||||
func (s *Service) SyncCredential(ctx context.Context, credentialID string) (domain.Job, error) {
|
||||
job := s.startJob(ctx, "cloudflare.sync", credentialID, "Connecting to Cloudflare")
|
||||
job := s.startJob(ctx, "provider.sync", credentialID, "Connecting to provider")
|
||||
fail := func(err error) (domain.Job, error) {
|
||||
job.State = domain.JobFailed
|
||||
job.Error = err.Error()
|
||||
@@ -586,6 +636,10 @@ func (s *Service) SyncCredential(ctx context.Context, credentialID string) (doma
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
job.Kind = credential.Provider + ".sync"
|
||||
job.Message = "Connecting to " + credential.Provider
|
||||
job.UpdatedAt = s.now().UTC()
|
||||
_ = s.repo.SaveJob(ctx, job)
|
||||
p, ok := s.providers[credential.Provider]
|
||||
if !ok {
|
||||
return fail(fmt.Errorf("provider %q is not registered", credential.Provider))
|
||||
@@ -653,13 +707,14 @@ func (s *Service) SyncCredential(ctx context.Context, credentialID string) (doma
|
||||
|
||||
accountByID := make(map[string]domain.RemoteAccount)
|
||||
for _, account := range verification.Accounts {
|
||||
normalizeAccount(&account)
|
||||
normalizeAccount(&account, credential.Provider)
|
||||
accountByID[account.ID] = account
|
||||
}
|
||||
returnedZoneIDs := make(map[string]struct{}, len(zones))
|
||||
newZoneIDs := make(map[string]struct{}, len(zones))
|
||||
for i := range zones {
|
||||
normalizeZone(&zones[i], "")
|
||||
accountProviderID := zones[i].AccountID
|
||||
normalizeZone(&zones[i], credential.Provider, "")
|
||||
key := zones[i].Provider + "\x00" + zones[i].ProviderID
|
||||
returnedZoneIDs[key] = struct{}{}
|
||||
if existing, known := existingZoneByProviderID[key]; known {
|
||||
@@ -676,10 +731,13 @@ func (s *Service) SyncCredential(ctx context.Context, credentialID string) (doma
|
||||
newZoneIDs[zones[i].ID] = struct{}{}
|
||||
}
|
||||
if _, exists := accountByID[zones[i].AccountID]; !exists {
|
||||
providerID := strings.TrimPrefix(zones[i].AccountID, "cfacct_")
|
||||
providerID := accountProviderID
|
||||
if credential.Provider == domain.ProviderCloudflare {
|
||||
providerID = strings.TrimPrefix(zones[i].AccountID, "cfacct_")
|
||||
}
|
||||
accountByID[zones[i].AccountID] = domain.RemoteAccount{
|
||||
ID: zones[i].AccountID, Provider: domain.ProviderCloudflare,
|
||||
ProviderID: providerID, Name: "Cloudflare account " + shortID(providerID), CreatedAt: s.now().UTC(),
|
||||
ID: zones[i].AccountID, Provider: credential.Provider,
|
||||
ProviderID: providerID, Name: credential.Provider + " account " + shortID(providerID), CreatedAt: s.now().UTC(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -714,7 +772,7 @@ func (s *Service) SyncCredential(ctx context.Context, credentialID string) (doma
|
||||
if visibilityErr != nil || !visible {
|
||||
continue
|
||||
}
|
||||
normalizeZone(&visibleZone, "")
|
||||
normalizeZone(&visibleZone, candidate.Provider, "")
|
||||
visibleZone.PreferredCredentialID = ""
|
||||
visibleZone.LastSyncedAt = &staleAt
|
||||
existing = visibleZone
|
||||
@@ -774,7 +832,7 @@ func (s *Service) SyncCredential(ctx context.Context, credentialID string) (doma
|
||||
if listErr == nil {
|
||||
now := s.now().UTC()
|
||||
for i := range records {
|
||||
normalizeRecord(&records[i], zone.ID)
|
||||
normalizeRecord(&records[i], zone.Provider, zone.ID)
|
||||
records[i].LastSyncedAt = &now
|
||||
}
|
||||
listErr = s.repo.ReplaceDNSRecords(groupCtx, zone.ID, records, now)
|
||||
@@ -842,7 +900,7 @@ func (s *Service) CreateDNSRecord(ctx context.Context, zoneID string, record dom
|
||||
)
|
||||
}
|
||||
s.observeZoneCapability(context.WithoutCancel(ctx), auth.CredentialID, zone.ID, "dns:write")
|
||||
normalizeRecord(&created, zone.ID)
|
||||
normalizeRecord(&created, zone.Provider, zone.ID)
|
||||
s.audit(context.WithoutCancel(ctx), "dns.create", created.ID, nil, created)
|
||||
if _, reconcileErr := s.reconcileDNSZone(ctx, zone, p, auth); reconcileErr != nil {
|
||||
return created, dnsMutationAppliedButUnreconciledError("create", reconcileErr)
|
||||
@@ -898,7 +956,7 @@ func (s *Service) PatchDNSRecord(ctx context.Context, zoneID, recordID string, d
|
||||
reconcileStructuredRecordData(&desired, remote)
|
||||
desired.Raw = append(json.RawMessage(nil), remote.Raw...)
|
||||
desired.Proxiable = remote.Proxiable
|
||||
normalizeRecord(&remote, zone.ID)
|
||||
normalizeRecord(&remote, zone.Provider, zone.ID)
|
||||
updated, mutationErr := p.PatchDNSRecord(ctx, auth, zone.ProviderID, cached.ProviderID, desired)
|
||||
if mutationErr != nil {
|
||||
if mutationFailureIsDefinitive(mutationErr) {
|
||||
@@ -909,7 +967,7 @@ func (s *Service) PatchDNSRecord(ctx context.Context, zoneID, recordID string, d
|
||||
)
|
||||
}
|
||||
s.observeZoneCapability(context.WithoutCancel(ctx), auth.CredentialID, zone.ID, "dns:write")
|
||||
normalizeRecord(&updated, zone.ID)
|
||||
normalizeRecord(&updated, zone.Provider, zone.ID)
|
||||
s.audit(context.WithoutCancel(ctx), "dns.patch", updated.ID, remote, updated)
|
||||
if _, reconcileErr := s.reconcileDNSZone(ctx, zone, p, auth); reconcileErr != nil {
|
||||
return updated, dnsMutationAppliedButUnreconciledError("patch", reconcileErr)
|
||||
@@ -952,7 +1010,7 @@ func (s *Service) DeleteDNSRecord(ctx context.Context, zoneID, recordID string)
|
||||
if !sameDNSRecordVersion(cached, remote) {
|
||||
return fmt.Errorf("%w: %s", ErrDNSConflict, cached.Name)
|
||||
}
|
||||
normalizeRecord(&remote, zone.ID)
|
||||
normalizeRecord(&remote, zone.Provider, zone.ID)
|
||||
if mutationErr := p.DeleteDNSRecord(ctx, auth, zone.ProviderID, cached.ProviderID); mutationErr != nil {
|
||||
if mutationFailureIsDefinitive(mutationErr) {
|
||||
return mutationErr
|
||||
@@ -991,7 +1049,7 @@ func (s *Service) ApplyDNSBatch(ctx context.Context, zoneID string, mutations []
|
||||
return DNSBatchResult{}, err
|
||||
}
|
||||
result := DNSBatchResult{Plan: planned.plan}
|
||||
if _, applyErr := planned.cloud.ApplyDNSBatch(ctx, planned.auth, planned.zone.ProviderID, planned.plan.Mutations); applyErr != nil {
|
||||
if _, applyErr := planned.batch.ApplyDNSBatch(ctx, planned.auth, planned.zone.ProviderID, planned.plan.Mutations); applyErr != nil {
|
||||
if mutationFailureIsDefinitive(applyErr) {
|
||||
return result, applyErr
|
||||
}
|
||||
@@ -1004,7 +1062,7 @@ func (s *Service) ApplyDNSBatch(ctx context.Context, zoneID string, mutations []
|
||||
if refreshErr == nil {
|
||||
now := s.now().UTC()
|
||||
for index := range records {
|
||||
normalizeRecord(&records[index], planned.zone.ID)
|
||||
normalizeRecord(&records[index], planned.zone.Provider, planned.zone.ID)
|
||||
records[index].LastSyncedAt = &now
|
||||
}
|
||||
result.Records = records
|
||||
@@ -1015,7 +1073,7 @@ func (s *Service) ApplyDNSBatch(ctx context.Context, zoneID string, mutations []
|
||||
}
|
||||
}
|
||||
return result, errors.Join(
|
||||
fmt.Errorf("Cloudflare batch outcome is unknown; synchronize and review before retrying: %w", applyErr),
|
||||
fmt.Errorf("%s DNS batch outcome is unknown; synchronize and review before retrying: %w", planned.zone.Provider, applyErr),
|
||||
refreshErr,
|
||||
)
|
||||
}
|
||||
@@ -1030,7 +1088,7 @@ func (s *Service) ApplyDNSBatch(ctx context.Context, zoneID string, mutations []
|
||||
}
|
||||
now := s.now().UTC()
|
||||
for index := range records {
|
||||
normalizeRecord(&records[index], planned.zone.ID)
|
||||
normalizeRecord(&records[index], planned.zone.Provider, planned.zone.ID)
|
||||
records[index].LastSyncedAt = &now
|
||||
}
|
||||
result.Records = records
|
||||
@@ -1056,7 +1114,7 @@ func mutationFailureIsDefinitive(err error) bool {
|
||||
// snapshot. It deliberately outlives cancellation of the mutation request, but
|
||||
// remains bounded so an interrupted client cannot leave reconciliation running
|
||||
// indefinitely.
|
||||
func (s *Service) reconcileDNSZone(ctx context.Context, zone domain.Zone, cloud provider.CloudProvider, auth provider.Auth) ([]domain.DNSRecord, error) {
|
||||
func (s *Service) reconcileDNSZone(ctx context.Context, zone domain.Zone, cloud provider.Provider, auth provider.Auth) ([]domain.DNSRecord, error) {
|
||||
reconcileCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dnsMutationReconcileTimeout)
|
||||
defer cancel()
|
||||
records, err := listAllRecords(reconcileCtx, cloud, auth, zone.ProviderID)
|
||||
@@ -1065,7 +1123,7 @@ func (s *Service) reconcileDNSZone(ctx context.Context, zone domain.Zone, cloud
|
||||
}
|
||||
now := s.now().UTC()
|
||||
for index := range records {
|
||||
normalizeRecord(&records[index], zone.ID)
|
||||
normalizeRecord(&records[index], zone.Provider, zone.ID)
|
||||
records[index].LastSyncedAt = &now
|
||||
}
|
||||
cacheErr := s.repo.ReplaceDNSRecords(reconcileCtx, zone.ID, records, now)
|
||||
@@ -1089,7 +1147,7 @@ func (s *Service) dnsMutationOutcomeUnknownError(
|
||||
before, after interface{},
|
||||
mutationErr error,
|
||||
zone domain.Zone,
|
||||
cloud provider.CloudProvider,
|
||||
cloud provider.Provider,
|
||||
auth provider.Auth,
|
||||
) error {
|
||||
s.audit(context.WithoutCancel(ctx), "dns."+action+".outcome_unknown", resourceID, before, after)
|
||||
@@ -1119,6 +1177,10 @@ func (s *Service) planDNSBatch(ctx context.Context, zoneID string, mutations []d
|
||||
if err != nil {
|
||||
return plannedDNSBatch{}, err
|
||||
}
|
||||
batch, ok := cloud.(provider.DNSBatchService)
|
||||
if !ok {
|
||||
return plannedDNSBatch{}, provider.Unsupported(zone.Provider, "DNS batch")
|
||||
}
|
||||
cachedRecords, err := s.repo.ListDNSRecords(ctx, zone.ID)
|
||||
if err != nil {
|
||||
return plannedDNSBatch{}, err
|
||||
@@ -1175,7 +1237,7 @@ func (s *Service) planDNSBatch(ctx context.Context, zoneID string, mutations []d
|
||||
return plannedDNSBatch{}, fmt.Errorf("DNS batch mutation %d: %w: %s", index, ErrDNSConflict, cached.Name)
|
||||
}
|
||||
remoteForPlan := cloneDNSRecord(remote)
|
||||
normalizeRecord(&remoteForPlan, zone.ID)
|
||||
normalizeRecord(&remoteForPlan, zone.Provider, zone.ID)
|
||||
plannedMutation.RecordID = cached.ProviderID
|
||||
plannedMutation.Before = &remoteForPlan
|
||||
if mutation.Kind == domain.MutationDelete {
|
||||
@@ -1212,7 +1274,7 @@ func (s *Service) planDNSBatch(ctx context.Context, zoneID string, mutations []d
|
||||
}
|
||||
plan.Mutations = append(plan.Mutations, plannedMutation)
|
||||
}
|
||||
return plannedDNSBatch{plan: plan, zone: zone, cloud: cloud, auth: auth}, nil
|
||||
return plannedDNSBatch{plan: plan, zone: zone, cloud: cloud, batch: batch, auth: auth}, nil
|
||||
}
|
||||
|
||||
func dnsMutationRecordID(mutation domain.DNSMutation) string {
|
||||
@@ -1293,7 +1355,11 @@ func (s *Service) TLSSettings(ctx context.Context, zoneID string, refresh bool)
|
||||
if err != nil {
|
||||
return domain.EdgeTLSSettings{}, err
|
||||
}
|
||||
settings, err := p.GetEdgeTLSSettings(ctx, auth, zone.ProviderID)
|
||||
tlsProvider, ok := p.(provider.EdgeTLSService)
|
||||
if !ok {
|
||||
return domain.EdgeTLSSettings{}, provider.Unsupported(zone.Provider, "edge TLS")
|
||||
}
|
||||
settings, err := tlsProvider.GetEdgeTLSSettings(ctx, auth, zone.ProviderID)
|
||||
if err != nil {
|
||||
return domain.EdgeTLSSettings{}, err
|
||||
}
|
||||
@@ -1313,10 +1379,14 @@ func (s *Service) EdgeCertificates(ctx context.Context, zoneID string) ([]domain
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tlsProvider, ok := p.(provider.EdgeTLSService)
|
||||
if !ok {
|
||||
return nil, provider.Unsupported(zone.Provider, "edge TLS")
|
||||
}
|
||||
const pageSize = 50
|
||||
values := make([]domain.EdgeCertificate, 0, pageSize)
|
||||
for page := 1; page <= 200; page++ {
|
||||
batch, listErr := p.ListEdgeCertificates(ctx, auth, zone.ProviderID, provider.PageRequest{Page: page, PerPage: pageSize})
|
||||
batch, listErr := tlsProvider.ListEdgeCertificates(ctx, auth, zone.ProviderID, provider.PageRequest{Page: page, PerPage: pageSize})
|
||||
if listErr != nil {
|
||||
return nil, listErr
|
||||
}
|
||||
@@ -1342,6 +1412,10 @@ func (s *Service) UpdateTLSSettings(ctx context.Context, zoneID string, desired
|
||||
if err != nil {
|
||||
return domain.EdgeTLSSettings{}, err
|
||||
}
|
||||
tlsProvider, ok := p.(provider.EdgeTLSService)
|
||||
if !ok {
|
||||
return domain.EdgeTLSSettings{}, provider.Unsupported(zone.Provider, "edge TLS")
|
||||
}
|
||||
baseline, err := s.repo.GetTLSSettings(ctx, zone.ID)
|
||||
if err != nil {
|
||||
return domain.EdgeTLSSettings{}, fmt.Errorf("load displayed TLS baseline: %w", err)
|
||||
@@ -1349,7 +1423,7 @@ func (s *Service) UpdateTLSSettings(ctx context.Context, zoneID string, desired
|
||||
if desired.LastSyncedAt != nil && baseline.LastSyncedAt != nil && !desired.LastSyncedAt.Equal(*baseline.LastSyncedAt) {
|
||||
return domain.EdgeTLSSettings{}, ErrTLSConflict
|
||||
}
|
||||
before, err := p.GetEdgeTLSSettings(ctx, auth, zone.ProviderID)
|
||||
before, err := tlsProvider.GetEdgeTLSSettings(ctx, auth, zone.ProviderID)
|
||||
if err != nil {
|
||||
return domain.EdgeTLSSettings{}, fmt.Errorf("re-fetch Cloudflare TLS settings: %w", err)
|
||||
}
|
||||
@@ -1369,7 +1443,7 @@ func (s *Service) UpdateTLSSettings(ctx context.Context, zoneID string, desired
|
||||
return before, nil
|
||||
}
|
||||
desired.ZoneID = zone.ProviderID
|
||||
updated, updateErr := p.UpdateEdgeTLSSettings(ctx, auth, zone.ProviderID, baseline, desired)
|
||||
updated, updateErr := tlsProvider.UpdateEdgeTLSSettings(ctx, auth, zone.ProviderID, baseline, desired)
|
||||
if updateErr != nil {
|
||||
reconcileCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
@@ -1380,7 +1454,7 @@ func (s *Service) UpdateTLSSettings(ctx context.Context, zoneID string, desired
|
||||
saveErr := s.repo.SaveTLSSettings(reconcileCtx, before)
|
||||
return before, errors.Join(updateErr, wrapError("save unchanged TLS settings", saveErr))
|
||||
}
|
||||
effective, refreshErr := p.GetEdgeTLSSettings(reconcileCtx, auth, zone.ProviderID)
|
||||
effective, refreshErr := tlsProvider.GetEdgeTLSSettings(reconcileCtx, auth, zone.ProviderID)
|
||||
if refreshErr != nil {
|
||||
return domain.EdgeTLSSettings{}, errors.Join(
|
||||
ErrTLSMutationOutcomeUnknown,
|
||||
@@ -1490,6 +1564,10 @@ func (s *Service) ObserveCredentialZoneCapability(ctx context.Context, credentia
|
||||
(capability != "dns:read" && capability != "dns:write" && capability != "tls:read" && capability != "tls:write") {
|
||||
return errors.New("unsupported observed credential capability")
|
||||
}
|
||||
credential, err := s.repo.GetCredential(ctx, credentialID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
zone, err := s.repo.GetZone(ctx, zoneReference)
|
||||
if err != nil {
|
||||
zones, listErr := s.repo.ListZones(ctx)
|
||||
@@ -1498,7 +1576,7 @@ func (s *Service) ObserveCredentialZoneCapability(ctx context.Context, credentia
|
||||
}
|
||||
zone = domain.Zone{}
|
||||
for _, candidate := range zones {
|
||||
if candidate.ProviderID == zoneReference {
|
||||
if candidate.Provider == credential.Provider && candidate.ProviderID == zoneReference {
|
||||
zone = candidate
|
||||
break
|
||||
}
|
||||
@@ -1507,10 +1585,6 @@ func (s *Service) ObserveCredentialZoneCapability(ctx context.Context, credentia
|
||||
return fmt.Errorf("zone %q for observed capability was not found", zoneReference)
|
||||
}
|
||||
}
|
||||
credential, err := s.repo.GetCredential(ctx, credentialID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if credential.Provider != zone.Provider {
|
||||
return errors.New("observed capability credential and zone providers differ")
|
||||
}
|
||||
@@ -1537,10 +1611,10 @@ func (s *Service) auth(ctx context.Context, credential domain.Credential) (provi
|
||||
if err != nil {
|
||||
return provider.Auth{}, fmt.Errorf("unlock credential %q: %w", credential.Label, err)
|
||||
}
|
||||
return provider.Auth{CredentialID: credential.ID, Token: string(secret), Kind: credential.Kind, AccountID: credential.AccountHint}, nil
|
||||
return provider.Auth{Provider: credential.Provider, CredentialID: credential.ID, Token: string(secret), Kind: credential.Kind, AccountID: credential.AccountHint}, nil
|
||||
}
|
||||
|
||||
func (s *Service) zoneProvider(ctx context.Context, zoneID string) (domain.Zone, provider.CloudProvider, provider.Auth, error) {
|
||||
func (s *Service) zoneProvider(ctx context.Context, zoneID string) (domain.Zone, provider.Provider, provider.Auth, error) {
|
||||
zone, err := s.repo.GetZone(ctx, zoneID)
|
||||
if err != nil {
|
||||
return domain.Zone{}, nil, provider.Auth{}, err
|
||||
@@ -1563,7 +1637,7 @@ func (s *Service) zoneProvider(ctx context.Context, zoneID string) (domain.Zone,
|
||||
return zone, p, auth, err
|
||||
}
|
||||
|
||||
func (s *Service) dnsZoneProvider(ctx context.Context, zoneID string) (domain.Zone, provider.CloudProvider, provider.Auth, error) {
|
||||
func (s *Service) dnsZoneProvider(ctx context.Context, zoneID string) (domain.Zone, provider.Provider, provider.Auth, error) {
|
||||
zone, cloud, auth, err := s.zoneProvider(ctx, zoneID)
|
||||
if err != nil {
|
||||
return domain.Zone{}, nil, provider.Auth{}, err
|
||||
@@ -1695,25 +1769,46 @@ func advancePage(request *provider.PageRequest, nextCursor string, responsePage,
|
||||
return false
|
||||
}
|
||||
|
||||
func normalizeAccount(account *domain.RemoteAccount) {
|
||||
func normalizeAccount(account *domain.RemoteAccount, providerName string) {
|
||||
if providerName == "" {
|
||||
providerName = account.Provider
|
||||
}
|
||||
if account.ProviderID == "" {
|
||||
account.ProviderID = strings.TrimPrefix(account.ID, "cfacct_")
|
||||
account.ProviderID = account.ID
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
account.ProviderID = strings.TrimPrefix(account.ProviderID, "cfacct_")
|
||||
}
|
||||
}
|
||||
account.Provider = providerName
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
account.ID = "cfacct_" + account.ProviderID
|
||||
} else {
|
||||
account.ID = stableID("account", providerName, account.ProviderID)
|
||||
}
|
||||
account.Provider = domain.ProviderCloudflare
|
||||
account.ID = "cfacct_" + account.ProviderID
|
||||
if account.CreatedAt.IsZero() {
|
||||
account.CreatedAt = time.Now().UTC()
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeZone(zone *domain.Zone, credentialID string) {
|
||||
if zone.ProviderID == "" {
|
||||
zone.ProviderID = strings.TrimPrefix(zone.ID, "cfzone_")
|
||||
func normalizeZone(zone *domain.Zone, providerName, credentialID string) {
|
||||
if providerName == "" {
|
||||
providerName = zone.Provider
|
||||
}
|
||||
zone.Provider = domain.ProviderCloudflare
|
||||
zone.ID = "cfzone_" + zone.ProviderID
|
||||
if !strings.HasPrefix(zone.AccountID, "cfacct_") {
|
||||
zone.AccountID = "cfacct_" + zone.AccountID
|
||||
if zone.ProviderID == "" {
|
||||
zone.ProviderID = zone.ID
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
zone.ProviderID = strings.TrimPrefix(zone.ProviderID, "cfzone_")
|
||||
}
|
||||
}
|
||||
zone.Provider = providerName
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
zone.ID = "cfzone_" + zone.ProviderID
|
||||
if !strings.HasPrefix(zone.AccountID, "cfacct_") {
|
||||
zone.AccountID = "cfacct_" + zone.AccountID
|
||||
}
|
||||
} else {
|
||||
zone.ID = stableID("zone", providerName, zone.ProviderID)
|
||||
zone.AccountID = stableID("account", providerName, zone.AccountID)
|
||||
}
|
||||
zone.PreferredCredentialID = credentialID
|
||||
if zone.Status == "" {
|
||||
@@ -1721,11 +1816,18 @@ func normalizeZone(zone *domain.Zone, credentialID string) {
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeRecord(record *domain.DNSRecord, zoneID string) {
|
||||
func normalizeRecord(record *domain.DNSRecord, providerName, zoneID string) {
|
||||
if record.ProviderID == "" {
|
||||
record.ProviderID = strings.TrimPrefix(record.ID, "cfrecord_")
|
||||
record.ProviderID = record.ID
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
record.ProviderID = strings.TrimPrefix(record.ProviderID, "cfrecord_")
|
||||
}
|
||||
}
|
||||
if providerName == domain.ProviderCloudflare {
|
||||
record.ID = "cfrecord_" + record.ProviderID
|
||||
} else {
|
||||
record.ID = stableID("record", providerName, zoneID, record.ProviderID)
|
||||
}
|
||||
record.ID = "cfrecord_" + record.ProviderID
|
||||
record.ZoneID = zoneID
|
||||
if unicodeName, err := idna.Lookup.ToUnicode(record.Name); err == nil {
|
||||
record.UnicodeName = unicodeName
|
||||
@@ -1797,7 +1899,7 @@ func validateRecordValue(record *domain.DNSRecord) error {
|
||||
// Empty TXT values are valid and intentionally preserved.
|
||||
}
|
||||
if record.Proxied && record.Type != domain.RecordA && record.Type != domain.RecordAAAA && record.Type != domain.RecordCNAME {
|
||||
return fmt.Errorf("record type %s cannot be Cloudflare proxied", record.Type)
|
||||
return fmt.Errorf("record type %s cannot be proxied by this provider", record.Type)
|
||||
}
|
||||
if record.Priority != nil && record.Type != domain.RecordMX && record.Type != domain.RecordSRV {
|
||||
return fmt.Errorf("record type %s does not use priority", record.Type)
|
||||
|
||||
@@ -132,7 +132,7 @@ func TestServiceMultiCredentialSyncAndDNSLifecycle(t *testing.T) {
|
||||
}
|
||||
|
||||
auth, providerZoneID, err := service.ResolveDNS01(ctx, "_acme-challenge.api.example.com.")
|
||||
if err != nil || auth.Token != "token-one" || providerZoneID != "zone-provider" {
|
||||
if err != nil || auth.Provider != domain.ProviderCloudflare || auth.CredentialID != first.ID || auth.Token != "token-one" || providerZoneID != "zone-provider" {
|
||||
t.Fatalf("DNS-01 resolution = %#v, %q, %v", auth, providerZoneID, err)
|
||||
}
|
||||
|
||||
@@ -1123,6 +1123,130 @@ func TestSetPreferredCredentialLiveProbePersistsZoneReadEvidence(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNS01RouterDispatchesExactProviderAndCredential(t *testing.T) {
|
||||
service := New(nil, nil)
|
||||
alpha := &routingProvider{name: "alpha"}
|
||||
beta := &routingProvider{name: "beta"}
|
||||
service.RegisterProvider("alpha", alpha)
|
||||
service.RegisterProvider("beta", beta)
|
||||
auth := provider.Auth{Provider: "beta", CredentialID: "credential-beta", Token: "beta-secret", Kind: domain.CredentialUserToken}
|
||||
|
||||
recordID, err := service.PresentDNS01(context.Background(), auth, "shared-zone-id", "_acme.example.", "value", "job-1")
|
||||
if err != nil || recordID != "beta-record" {
|
||||
t.Fatalf("PresentDNS01 = %q, %v", recordID, err)
|
||||
}
|
||||
if err := service.CleanupDNS01(context.Background(), auth, "shared-zone-id", recordID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reconciledID, found, err := service.ReconcileDNS01(context.Background(), auth, "shared-zone-id", "_acme.example.", "hash", "job-1")
|
||||
if err != nil || !found || reconciledID != "beta-reconciled" {
|
||||
t.Fatalf("ReconcileDNS01 = %q, %v, %v", reconciledID, found, err)
|
||||
}
|
||||
if len(alpha.calls) != 0 {
|
||||
t.Fatalf("unselected provider received calls: %#v", alpha.calls)
|
||||
}
|
||||
if len(beta.calls) != 3 {
|
||||
t.Fatalf("selected provider calls = %#v", beta.calls)
|
||||
}
|
||||
for _, call := range beta.calls {
|
||||
if call.auth != auth || call.zoneID != "shared-zone-id" {
|
||||
t.Fatalf("routed call changed auth/zone: %#v", call)
|
||||
}
|
||||
}
|
||||
if _, err := service.PresentDNS01(context.Background(), provider.Auth{CredentialID: "credential-beta"}, "shared-zone-id", "fqdn", "value", "job"); err == nil || !strings.Contains(err.Error(), "no provider identity") {
|
||||
t.Fatalf("provider-less auth was routed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalProviderCapabilitiesFailClearly(t *testing.T) {
|
||||
fake := newFakeCloudProvider()
|
||||
service, _, zone := newBatchTestService(t, fake)
|
||||
service.RegisterProvider(domain.ProviderCloudflare, coreOnlyProvider{Provider: fake})
|
||||
|
||||
mutation := domain.DNSMutation{Kind: domain.MutationCreate, After: &domain.DNSRecord{Type: domain.RecordA, Name: "new", Content: "192.0.2.20", TTL: 300}}
|
||||
if _, err := service.PlanDNSBatch(context.Background(), zone.ID, []domain.DNSMutation{mutation}); !errors.Is(err, provider.ErrCapabilityUnsupported) || !strings.Contains(err.Error(), "DNS batch") {
|
||||
t.Fatalf("unsupported batch error = %v", err)
|
||||
}
|
||||
if _, err := service.TLSSettings(context.Background(), zone.ID, true); !errors.Is(err, provider.ErrCapabilityUnsupported) || !strings.Contains(err.Error(), "edge TLS") {
|
||||
t.Fatalf("unsupported TLS read error = %v", err)
|
||||
}
|
||||
if _, err := service.EdgeCertificates(context.Background(), zone.ID); !errors.Is(err, provider.ErrCapabilityUnsupported) {
|
||||
t.Fatalf("unsupported TLS inventory error = %v", err)
|
||||
}
|
||||
if _, err := service.UpdateTLSSettings(context.Background(), zone.ID, domain.EdgeTLSSettings{}); !errors.Is(err, provider.ErrCapabilityUnsupported) {
|
||||
t.Fatalf("unsupported TLS update error = %v", err)
|
||||
}
|
||||
auth, err := service.ResolveCredential(context.Background(), zone.PreferredCredentialID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := service.ReconcileDNS01(context.Background(), auth, zone.ProviderID, "_acme.example.", "hash", "job"); !errors.Is(err, provider.ErrCapabilityUnsupported) || !strings.Contains(err.Error(), "DNS-01 reconciliation") {
|
||||
t.Fatalf("unsupported DNS-01 reconciliation error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderNeutralNormalizationPreservesCloudflareAndIsolatesRemoteIDs(t *testing.T) {
|
||||
cloudflareAccount := domain.RemoteAccount{ID: "remote-account"}
|
||||
normalizeAccount(&cloudflareAccount, domain.ProviderCloudflare)
|
||||
if cloudflareAccount.ID != "cfacct_remote-account" || cloudflareAccount.Provider != domain.ProviderCloudflare {
|
||||
t.Fatalf("Cloudflare account normalization changed: %#v", cloudflareAccount)
|
||||
}
|
||||
cloudflareZone := domain.Zone{ID: "remote-zone", AccountID: "remote-account"}
|
||||
normalizeZone(&cloudflareZone, domain.ProviderCloudflare, "credential")
|
||||
if cloudflareZone.ID != "cfzone_remote-zone" || cloudflareZone.AccountID != "cfacct_remote-account" {
|
||||
t.Fatalf("Cloudflare zone normalization changed: %#v", cloudflareZone)
|
||||
}
|
||||
cloudflareRecord := domain.DNSRecord{ID: "remote-record"}
|
||||
normalizeRecord(&cloudflareRecord, domain.ProviderCloudflare, cloudflareZone.ID)
|
||||
if cloudflareRecord.ID != "cfrecord_remote-record" {
|
||||
t.Fatalf("Cloudflare record normalization changed: %#v", cloudflareRecord)
|
||||
}
|
||||
|
||||
firstZone := domain.Zone{ID: "shared-zone", AccountID: "shared-account"}
|
||||
secondZone := firstZone
|
||||
normalizeZone(&firstZone, "provider-a", "credential-a")
|
||||
normalizeZone(&secondZone, "provider-b", "credential-b")
|
||||
if firstZone.ID == secondZone.ID || firstZone.AccountID == secondZone.AccountID {
|
||||
t.Fatalf("provider-local zone/account IDs collided: %#v / %#v", firstZone, secondZone)
|
||||
}
|
||||
firstRecord := domain.DNSRecord{ID: "shared-record"}
|
||||
secondRecord := firstRecord
|
||||
normalizeRecord(&firstRecord, "provider-a", firstZone.ID)
|
||||
normalizeRecord(&secondRecord, "provider-b", secondZone.ID)
|
||||
if firstRecord.ID == secondRecord.ID || firstRecord.ProviderID != "shared-record" || secondRecord.ProviderID != "shared-record" {
|
||||
t.Fatalf("provider-local record IDs were not isolated: %#v / %#v", firstRecord, secondRecord)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObservedCapabilityProviderIDFallbackCannotCrossProviders(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
service, repository, cloudflareZone := newBatchTestService(t, newFakeCloudProvider())
|
||||
credential, err := repository.GetCredential(ctx, cloudflareZone.PreferredCredentialID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreignAccount := domain.RemoteAccount{ID: stableID("account", "other", "account"), Provider: "other", ProviderID: "account", Name: "Other", CreatedAt: time.Now().UTC()}
|
||||
if err := repository.SaveAccounts(ctx, []domain.RemoteAccount{foreignAccount}, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
foreignZone := domain.Zone{ID: stableID("zone", "other", cloudflareZone.ProviderID), Provider: "other", ProviderID: cloudflareZone.ProviderID, AccountID: foreignAccount.ID, Name: "aaa-other.example", Status: domain.ZoneActive}
|
||||
if err := repository.SaveZones(ctx, []domain.Zone{foreignZone}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := service.ObserveCredentialZoneCapability(ctx, credential.ID, cloudflareZone.ProviderID, "tls:write"); err != nil {
|
||||
t.Fatalf("provider-scoped fallback: %v", err)
|
||||
}
|
||||
cloudflareObserved, err := repository.HasCredentialZoneCapability(ctx, credential.ID, cloudflareZone.ID, "tls:write")
|
||||
if err != nil || !cloudflareObserved {
|
||||
t.Fatalf("Cloudflare observation = %v, %v", cloudflareObserved, err)
|
||||
}
|
||||
foreignObserved, err := repository.HasCredentialZoneCapability(ctx, credential.ID, foreignZone.ID, "tls:write")
|
||||
if err != nil || foreignObserved {
|
||||
t.Fatalf("foreign observation = %v, %v", foreignObserved, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialDeleteKeepsMetadataWhenVaultDeleteFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fake := newFakeCloudProvider()
|
||||
@@ -1323,6 +1447,53 @@ type providerRequest struct {
|
||||
Cursor string
|
||||
}
|
||||
|
||||
type coreOnlyProvider struct{ provider.Provider }
|
||||
|
||||
type routingCall struct {
|
||||
action string
|
||||
auth provider.Auth
|
||||
zoneID string
|
||||
}
|
||||
|
||||
type routingProvider struct {
|
||||
name string
|
||||
calls []routingCall
|
||||
}
|
||||
|
||||
func (p *routingProvider) VerifyCredential(context.Context, provider.Auth) (provider.Verification, error) {
|
||||
return provider.Verification{Status: domain.CredentialValid}, nil
|
||||
}
|
||||
func (p *routingProvider) ListZones(context.Context, provider.Auth, provider.PageRequest) (provider.ZonePage, error) {
|
||||
return provider.ZonePage{}, nil
|
||||
}
|
||||
func (p *routingProvider) ListDNSRecords(context.Context, provider.Auth, string, provider.PageRequest) (provider.RecordPage, error) {
|
||||
return provider.RecordPage{}, nil
|
||||
}
|
||||
func (p *routingProvider) GetDNSRecord(context.Context, provider.Auth, string, string) (domain.DNSRecord, error) {
|
||||
return domain.DNSRecord{}, nil
|
||||
}
|
||||
func (p *routingProvider) CreateDNSRecord(context.Context, provider.Auth, string, domain.DNSRecord) (domain.DNSRecord, error) {
|
||||
return domain.DNSRecord{}, nil
|
||||
}
|
||||
func (p *routingProvider) PatchDNSRecord(context.Context, provider.Auth, string, string, domain.DNSRecord) (domain.DNSRecord, error) {
|
||||
return domain.DNSRecord{}, nil
|
||||
}
|
||||
func (p *routingProvider) DeleteDNSRecord(context.Context, provider.Auth, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (p *routingProvider) PresentDNS01(_ context.Context, auth provider.Auth, zoneID, _, _, _ string) (string, error) {
|
||||
p.calls = append(p.calls, routingCall{action: "present", auth: auth, zoneID: zoneID})
|
||||
return p.name + "-record", nil
|
||||
}
|
||||
func (p *routingProvider) CleanupDNS01(_ context.Context, auth provider.Auth, zoneID, _ string) error {
|
||||
p.calls = append(p.calls, routingCall{action: "cleanup", auth: auth, zoneID: zoneID})
|
||||
return nil
|
||||
}
|
||||
func (p *routingProvider) ReconcileDNS01(_ context.Context, auth provider.Auth, zoneID, _, _, _ string) (string, bool, error) {
|
||||
p.calls = append(p.calls, routingCall{action: "reconcile", auth: auth, zoneID: zoneID})
|
||||
return p.name + "-reconciled", true, nil
|
||||
}
|
||||
|
||||
type paginatedZoneProvider struct{ requests []providerRequest }
|
||||
|
||||
func (p *paginatedZoneProvider) ListZones(_ context.Context, _ provider.Auth, request provider.PageRequest) (provider.ZonePage, error) {
|
||||
|
||||
@@ -76,7 +76,7 @@ func Open(ctx context.Context, options Options) (*Runtime, error) {
|
||||
application.RegisterProvider("cloudflare", cloudflareClient)
|
||||
|
||||
httpClient := &http.Client{Timeout: 45 * time.Second}
|
||||
engine := certificates.NewEngine(repository, vault, cloudflareClient, application.ResolveDNS01,
|
||||
engine := certificates.NewEngine(repository, vault, application, application.ResolveDNS01,
|
||||
certificates.WithACMEHTTPClient(httpClient, "DomainOps/1"),
|
||||
certificates.WithPreflight(application.CertificatePreflight),
|
||||
certificates.WithDNSWriteObserver(func(observeCtx context.Context, credentialID, providerZoneID string) error {
|
||||
@@ -97,7 +97,7 @@ func Open(ctx context.Context, options Options) (*Runtime, error) {
|
||||
recoveryErr := errors.Join(
|
||||
certificates.RecoverACMEAccountCommitIntents(cleanupCtx, repository, vault),
|
||||
certificates.RecoverCertificateCommitIntents(cleanupCtx, repository, vault, paths.Certificates),
|
||||
certificates.CleanupOpenChallenges(cleanupCtx, repository, cloudflareClient, application.ResolveDNS01, application.ResolveCredential),
|
||||
certificates.CleanupOpenChallenges(cleanupCtx, repository, application, application.ResolveDNS01, application.ResolveCredential),
|
||||
certificateService.RepairManagedCurrentLinks(cleanupCtx),
|
||||
)
|
||||
return reconcileJobsAfterRecovery(recoveryErr, func() error {
|
||||
@@ -148,7 +148,7 @@ func (r *Runtime) Recover(ctx context.Context) error {
|
||||
recoveryErr := errors.Join(
|
||||
certificates.RecoverACMEAccountCommitIntents(ctx, r.Repository, r.Vault),
|
||||
certificates.RecoverCertificateCommitIntents(ctx, r.Repository, r.Vault, r.Paths.Certificates),
|
||||
certificates.CleanupOpenChallenges(ctx, r.Repository, r.Cloudflare, r.Application.ResolveDNS01, r.Application.ResolveCredential),
|
||||
certificates.CleanupOpenChallenges(ctx, r.Repository, r.Application, r.Application.ResolveDNS01, r.Application.ResolveCredential),
|
||||
r.Certificates.RepairManagedCurrentLinks(ctx),
|
||||
)
|
||||
return reconcileJobsAfterRecovery(recoveryErr, func() error {
|
||||
|
||||
@@ -3,6 +3,7 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
)
|
||||
@@ -38,6 +39,10 @@ func AccessFailureIsAuthoritative(err error) bool {
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
// Provider is the stable registry identity used to route this credential.
|
||||
// It travels with the secret so delayed DNS-01 cleanup cannot be redirected
|
||||
// to a different provider that happens to use the same remote zone ID.
|
||||
Provider string
|
||||
CredentialID string
|
||||
Token string
|
||||
Kind domain.CredentialKind
|
||||
@@ -118,11 +123,40 @@ type EdgeTLSService interface {
|
||||
ListEdgeCertificates(context.Context, Auth, string, PageRequest) ([]domain.EdgeCertificate, error)
|
||||
}
|
||||
|
||||
type CloudProvider interface {
|
||||
// Provider is the mandatory provider contract. DNS batching and edge TLS are
|
||||
// deliberately optional: a provider with safe single-record DNS operations
|
||||
// and DNS-01 support can be registered without pretending to implement them.
|
||||
type Provider interface {
|
||||
CredentialVerifier
|
||||
ZoneInventory
|
||||
DNSRecordService
|
||||
DNSBatchService
|
||||
DNS01Solver
|
||||
}
|
||||
|
||||
// CloudProvider retains the original all-capabilities contract for source
|
||||
// compatibility. New registrations should depend on Provider and discover
|
||||
// these optional capabilities with interface assertions.
|
||||
type CloudProvider interface {
|
||||
Provider
|
||||
DNSBatchService
|
||||
EdgeTLSService
|
||||
}
|
||||
|
||||
var ErrCapabilityUnsupported = errors.New("provider capability is not supported")
|
||||
|
||||
// UnsupportedCapabilityError identifies the exact optional feature and
|
||||
// provider which cannot satisfy an operation.
|
||||
type UnsupportedCapabilityError struct {
|
||||
Provider string
|
||||
Capability string
|
||||
}
|
||||
|
||||
func (e *UnsupportedCapabilityError) Error() string {
|
||||
return fmt.Sprintf("provider %q does not support %s", e.Provider, e.Capability)
|
||||
}
|
||||
|
||||
func (e *UnsupportedCapabilityError) Unwrap() error { return ErrCapabilityUnsupported }
|
||||
|
||||
func Unsupported(providerName, capability string) error {
|
||||
return &UnsupportedCapabilityError{Provider: providerName, Capability: capability}
|
||||
}
|
||||
@@ -40,7 +40,8 @@ type Options struct {
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Client implements provider.CloudProvider.
|
||||
// Client implements the mandatory provider contract and Cloudflare's optional
|
||||
// batch, DNS-01 recovery, and edge-TLS capabilities.
|
||||
type Client struct {
|
||||
baseURL string
|
||||
httpClient HTTPDoer
|
||||
@@ -48,7 +49,12 @@ type Client struct {
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
var _ provider.CloudProvider = (*Client)(nil)
|
||||
var (
|
||||
_ provider.Provider = (*Client)(nil)
|
||||
_ provider.DNSBatchService = (*Client)(nil)
|
||||
_ provider.DNS01Reconciler = (*Client)(nil)
|
||||
_ provider.EdgeTLSService = (*Client)(nil)
|
||||
)
|
||||
|
||||
// New returns a production Cloudflare client.
|
||||
func New() *Client {
|
||||
|
||||
@@ -19,6 +19,7 @@ var fixedNow = time.Date(2026, time.July, 11, 9, 30, 0, 0, time.UTC)
|
||||
|
||||
func testAuth() provider.Auth {
|
||||
return provider.Auth{
|
||||
Provider: domain.ProviderCloudflare,
|
||||
CredentialID: "cred-1",
|
||||
Token: "test-secret-token",
|
||||
Kind: domain.CredentialUserToken,
|
||||
|
||||
+382
-8
@@ -29,6 +29,8 @@ type Backend interface {
|
||||
Jobs(context.Context, int) ([]domain.Job, error)
|
||||
Audit(context.Context, int) ([]domain.AuditEvent, error)
|
||||
AddCloudflareCredential(context.Context, app.AddCredentialInput) (domain.Credential, error)
|
||||
DeleteCredential(context.Context, string) error
|
||||
SetZonePreferredCredential(context.Context, string, string) (domain.Zone, error)
|
||||
SyncAll(context.Context) ([]domain.Job, error)
|
||||
CreateDNSRecord(context.Context, string, domain.DNSRecord) (domain.DNSRecord, error)
|
||||
PatchDNSRecord(context.Context, string, string, domain.DNSRecord) (domain.DNSRecord, error)
|
||||
@@ -123,9 +125,29 @@ type Model struct {
|
||||
unlockFocus int
|
||||
unlockInputs []textinput.Model
|
||||
|
||||
addCredential bool
|
||||
credentialFocus int
|
||||
credentialInputs []textinput.Model
|
||||
addCredential bool
|
||||
credentialFocus int
|
||||
credentialInputs []textinput.Model
|
||||
removeCredential bool
|
||||
removeCredentialInput textinput.Model
|
||||
removeCredentialID string
|
||||
removeCredentialExpected string
|
||||
removeCredentialKind domain.CredentialKind
|
||||
removeCredentialAccountHint string
|
||||
removeCredentialZoneIDs []string
|
||||
removeCredentialZoneNames []string
|
||||
|
||||
preferCredential bool
|
||||
preferCredentialFocus int
|
||||
preferCredentialInputs []textinput.Model
|
||||
preferZoneID string
|
||||
preferZoneExpectedName string
|
||||
preferZoneProvider string
|
||||
preferZoneAccountID string
|
||||
preferOriginalCredentialID string
|
||||
preferResolvedCredentialID string
|
||||
preferResolvedCredentialLabel string
|
||||
preferCredentialSelection string
|
||||
|
||||
editRecord bool
|
||||
recordEditing bool
|
||||
@@ -342,6 +364,12 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if m.addCredential {
|
||||
return m.updateCredentialForm(message)
|
||||
}
|
||||
if m.removeCredential {
|
||||
return m.updateRemoveCredentialForm(message)
|
||||
}
|
||||
if m.preferCredential {
|
||||
return m.updatePreferredCredentialForm(message)
|
||||
}
|
||||
if m.editRecord {
|
||||
return m.updateRecordForm(message)
|
||||
}
|
||||
@@ -406,6 +434,11 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.openCredentialForm()
|
||||
return m, textinput.Blink
|
||||
}
|
||||
case "p":
|
||||
if m.screen == screenZones && len(m.filteredZones()) > 0 {
|
||||
m.openPreferredCredentialForm()
|
||||
return m, textinput.Blink
|
||||
}
|
||||
case "n":
|
||||
if m.screen == screenDNS && len(m.zones) > 0 {
|
||||
m.openRecordForm(false)
|
||||
@@ -436,6 +469,10 @@ func (m *Model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return m, textinput.Blink
|
||||
}
|
||||
case "d":
|
||||
if m.screen == screenAccounts && len(m.filteredCredentials()) > 0 {
|
||||
m.openRemoveCredentialForm()
|
||||
return m, textinput.Blink
|
||||
}
|
||||
if m.screen == screenDNS && len(m.filteredRecords()) > 0 {
|
||||
m.confirmDelete = true
|
||||
}
|
||||
@@ -792,6 +829,313 @@ func (m *Model) clearCredentialForm() {
|
||||
m.addCredential = false
|
||||
}
|
||||
|
||||
func (m *Model) openRemoveCredentialForm() {
|
||||
credentials := m.filteredCredentials()
|
||||
if len(credentials) == 0 {
|
||||
return
|
||||
}
|
||||
credential := credentials[min(m.rowOffset, len(credentials)-1)]
|
||||
m.removeCredentialZoneIDs = nil
|
||||
m.removeCredentialZoneNames = nil
|
||||
input := textinput.New()
|
||||
input.Prompt = ""
|
||||
input.Placeholder = "Type the exact connection label"
|
||||
input.SetWidth(52)
|
||||
input.Focus()
|
||||
m.removeCredentialInput = input
|
||||
m.removeCredentialID = credential.ID
|
||||
m.removeCredentialExpected = credential.Label
|
||||
m.removeCredentialKind = credential.Kind
|
||||
m.removeCredentialAccountHint = credential.AccountHint
|
||||
for _, zone := range m.zones {
|
||||
if zone.PreferredCredentialID == credential.ID {
|
||||
m.removeCredentialZoneIDs = append(m.removeCredentialZoneIDs, zone.ID)
|
||||
m.removeCredentialZoneNames = append(m.removeCredentialZoneNames, zone.Name)
|
||||
}
|
||||
}
|
||||
m.removeCredential = true
|
||||
m.err = nil
|
||||
}
|
||||
|
||||
func (m *Model) updateRemoveCredentialForm(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if key, ok := message.(tea.KeyPressMsg); ok {
|
||||
switch key.String() {
|
||||
case "esc":
|
||||
m.clearRemoveCredentialForm()
|
||||
return m, nil
|
||||
case "enter":
|
||||
if m.mutationFormBlocked() {
|
||||
return m, nil
|
||||
}
|
||||
credential, ok := m.credentialByID(m.removeCredentialID)
|
||||
if !ok || credential.Label != m.removeCredentialExpected {
|
||||
m.err = errors.New("the selected connection changed; cancel and select it again")
|
||||
return m, nil
|
||||
}
|
||||
if !m.removeCredentialRoutesUnchanged() {
|
||||
m.err = errors.New("the affected zone routes changed; cancel and review the removal again")
|
||||
return m, nil
|
||||
}
|
||||
if m.removeCredentialInput.Value() != m.removeCredentialExpected {
|
||||
m.err = fmt.Errorf("type %q exactly to confirm removal", m.removeCredentialExpected)
|
||||
return m, nil
|
||||
}
|
||||
credentialID := m.removeCredentialID
|
||||
label := m.removeCredentialExpected
|
||||
m.clearRemoveCredentialForm()
|
||||
m.busy = true
|
||||
return m, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
|
||||
defer cancel()
|
||||
err := m.backend.DeleteCredential(ctx, credentialID)
|
||||
return operationMsg{message: "Removed Cloudflare connection " + label, err: err, reload: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.removeCredentialInput, cmd = m.removeCredentialInput.Update(message)
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
func (m *Model) clearRemoveCredentialForm() {
|
||||
m.removeCredentialInput.SetValue("")
|
||||
m.removeCredentialInput.Blur()
|
||||
m.removeCredential = false
|
||||
m.removeCredentialID = ""
|
||||
m.removeCredentialExpected = ""
|
||||
m.removeCredentialKind = ""
|
||||
m.removeCredentialAccountHint = ""
|
||||
m.removeCredentialZoneIDs = nil
|
||||
m.removeCredentialZoneNames = nil
|
||||
}
|
||||
|
||||
func (m *Model) removeCredentialRoutesUnchanged() bool {
|
||||
if len(m.removeCredentialZoneIDs) != len(m.removeCredentialZoneNames) {
|
||||
return false
|
||||
}
|
||||
expected := make(map[string]string, len(m.removeCredentialZoneIDs))
|
||||
for index, zoneID := range m.removeCredentialZoneIDs {
|
||||
expected[zoneID] = m.removeCredentialZoneNames[index]
|
||||
}
|
||||
seen := 0
|
||||
for _, zone := range m.zones {
|
||||
if zone.PreferredCredentialID != m.removeCredentialID {
|
||||
continue
|
||||
}
|
||||
name, ok := expected[zone.ID]
|
||||
if !ok || name != zone.Name {
|
||||
return false
|
||||
}
|
||||
seen++
|
||||
}
|
||||
return seen == len(expected)
|
||||
}
|
||||
|
||||
func (m *Model) openPreferredCredentialForm() {
|
||||
zone, ok := m.selectedZone()
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
newInput := func(placeholder string) textinput.Model {
|
||||
input := textinput.New()
|
||||
input.Prompt = ""
|
||||
input.Placeholder = placeholder
|
||||
input.SetWidth(54)
|
||||
return input
|
||||
}
|
||||
m.preferCredentialInputs = []textinput.Model{
|
||||
newInput("Credential ID or unique connection label"),
|
||||
newInput("Type the exact zone name"),
|
||||
}
|
||||
m.preferCredentialInputs[0].Focus()
|
||||
m.preferCredentialFocus = 0
|
||||
m.preferZoneID = zone.ID
|
||||
m.preferZoneExpectedName = zone.Name
|
||||
m.preferZoneProvider = zone.Provider
|
||||
m.preferZoneAccountID = zone.AccountID
|
||||
m.preferOriginalCredentialID = zone.PreferredCredentialID
|
||||
m.preferResolvedCredentialID = ""
|
||||
m.preferResolvedCredentialLabel = ""
|
||||
m.preferCredentialSelection = ""
|
||||
m.preferCredential = true
|
||||
m.err = nil
|
||||
}
|
||||
|
||||
func (m *Model) updatePreferredCredentialForm(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if key, ok := message.(tea.KeyPressMsg); ok {
|
||||
switch key.String() {
|
||||
case "esc":
|
||||
m.clearPreferredCredentialForm()
|
||||
return m, nil
|
||||
case "tab", "down":
|
||||
if m.preferCredentialFocus == 0 && !m.capturePreferredCredential() {
|
||||
return m, nil
|
||||
}
|
||||
m.focusPreferredCredential(1)
|
||||
return m, nil
|
||||
case "shift+tab", "up":
|
||||
if m.preferCredentialFocus == 0 && !m.capturePreferredCredential() {
|
||||
return m, nil
|
||||
}
|
||||
m.focusPreferredCredential(-1)
|
||||
return m, nil
|
||||
case "enter":
|
||||
if m.preferCredentialFocus < len(m.preferCredentialInputs)-1 {
|
||||
if !m.capturePreferredCredential() {
|
||||
return m, nil
|
||||
}
|
||||
m.focusPreferredCredential(1)
|
||||
return m, nil
|
||||
}
|
||||
if m.mutationFormBlocked() {
|
||||
return m, nil
|
||||
}
|
||||
zone, ok := m.zoneByID(m.preferZoneID)
|
||||
if !ok || zone.Name != m.preferZoneExpectedName || zone.Provider != m.preferZoneProvider || zone.AccountID != m.preferZoneAccountID || zone.PreferredCredentialID != m.preferOriginalCredentialID {
|
||||
m.err = errors.New("the selected zone or its route changed; cancel and select it again")
|
||||
return m, nil
|
||||
}
|
||||
if m.preferCredentialInputs[1].Value() != m.preferZoneExpectedName {
|
||||
m.err = fmt.Errorf("type %q exactly to confirm the routing change", m.preferZoneExpectedName)
|
||||
return m, nil
|
||||
}
|
||||
if m.preferResolvedCredentialID == "" || strings.TrimSpace(m.preferCredentialInputs[0].Value()) != m.preferCredentialSelection {
|
||||
m.err = errors.New("select the connection again before confirming")
|
||||
return m, nil
|
||||
}
|
||||
credential, ok := m.credentialByID(m.preferResolvedCredentialID)
|
||||
if !ok || credential.Label != m.preferResolvedCredentialLabel {
|
||||
m.err = errors.New("the selected connection changed; select it again")
|
||||
return m, nil
|
||||
}
|
||||
if _, err := validatePreferredCredential(credential, zone); err != nil {
|
||||
m.err = err
|
||||
return m, nil
|
||||
}
|
||||
zoneID := m.preferZoneID
|
||||
credentialID := credential.ID
|
||||
zoneName := m.preferZoneExpectedName
|
||||
m.clearPreferredCredentialForm()
|
||||
m.busy = true
|
||||
return m, func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
_, err := m.backend.SetZonePreferredCredential(ctx, zoneID, credentialID)
|
||||
return operationMsg{message: "Preferred connection updated for " + zoneName, err: err, reload: true}
|
||||
}
|
||||
}
|
||||
}
|
||||
var cmd tea.Cmd
|
||||
m.preferCredentialInputs[m.preferCredentialFocus], cmd = m.preferCredentialInputs[m.preferCredentialFocus].Update(message)
|
||||
if m.preferCredentialFocus == 0 {
|
||||
m.preferResolvedCredentialID = ""
|
||||
m.preferResolvedCredentialLabel = ""
|
||||
m.preferCredentialSelection = ""
|
||||
}
|
||||
return m, cmd
|
||||
}
|
||||
|
||||
func (m *Model) capturePreferredCredential() bool {
|
||||
zone, ok := m.zoneByID(m.preferZoneID)
|
||||
if !ok || zone.Name != m.preferZoneExpectedName || zone.Provider != m.preferZoneProvider || zone.AccountID != m.preferZoneAccountID || zone.PreferredCredentialID != m.preferOriginalCredentialID {
|
||||
m.err = errors.New("the selected zone or its route changed; cancel and select it again")
|
||||
return false
|
||||
}
|
||||
selection := strings.TrimSpace(m.preferCredentialInputs[0].Value())
|
||||
credential, err := m.resolvePreferredCredential(selection, zone)
|
||||
if err != nil {
|
||||
m.err = err
|
||||
return false
|
||||
}
|
||||
m.preferResolvedCredentialID = credential.ID
|
||||
m.preferResolvedCredentialLabel = credential.Label
|
||||
m.preferCredentialSelection = selection
|
||||
m.err = nil
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *Model) focusPreferredCredential(delta int) {
|
||||
m.preferCredentialInputs[m.preferCredentialFocus].Blur()
|
||||
m.preferCredentialFocus = (m.preferCredentialFocus + delta + len(m.preferCredentialInputs)) % len(m.preferCredentialInputs)
|
||||
m.preferCredentialInputs[m.preferCredentialFocus].Focus()
|
||||
}
|
||||
|
||||
func (m *Model) clearPreferredCredentialForm() {
|
||||
for i := range m.preferCredentialInputs {
|
||||
m.preferCredentialInputs[i].SetValue("")
|
||||
m.preferCredentialInputs[i].Blur()
|
||||
}
|
||||
m.preferCredential = false
|
||||
m.preferCredentialFocus = 0
|
||||
m.preferZoneID = ""
|
||||
m.preferZoneExpectedName = ""
|
||||
m.preferZoneProvider = ""
|
||||
m.preferZoneAccountID = ""
|
||||
m.preferOriginalCredentialID = ""
|
||||
m.preferResolvedCredentialID = ""
|
||||
m.preferResolvedCredentialLabel = ""
|
||||
m.preferCredentialSelection = ""
|
||||
}
|
||||
|
||||
func (m *Model) resolvePreferredCredential(value string, zone domain.Zone) (domain.Credential, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return domain.Credential{}, errors.New("a credential ID or connection label is required")
|
||||
}
|
||||
for _, credential := range m.credentials {
|
||||
if credential.ID == value {
|
||||
return validatePreferredCredential(credential, zone)
|
||||
}
|
||||
}
|
||||
matches := make([]domain.Credential, 0, 1)
|
||||
for _, credential := range m.credentials {
|
||||
if strings.EqualFold(strings.TrimSpace(credential.Label), value) {
|
||||
matches = append(matches, credential)
|
||||
}
|
||||
}
|
||||
switch len(matches) {
|
||||
case 0:
|
||||
return domain.Credential{}, fmt.Errorf("connection %q is not synchronized; use an ID shown in Accounts", value)
|
||||
case 1:
|
||||
return validatePreferredCredential(matches[0], zone)
|
||||
default:
|
||||
return domain.Credential{}, fmt.Errorf("connection label %q is ambiguous across %d credentials; use the credential ID", value, len(matches))
|
||||
}
|
||||
}
|
||||
|
||||
func validatePreferredCredential(credential domain.Credential, zone domain.Zone) (domain.Credential, error) {
|
||||
if credential.Provider != zone.Provider {
|
||||
return domain.Credential{}, fmt.Errorf("connection %q uses provider %q, not %q", credential.Label, credential.Provider, zone.Provider)
|
||||
}
|
||||
if credential.Status != domain.CredentialValid {
|
||||
return domain.Credential{}, fmt.Errorf("connection %q is %s; synchronize or replace it before routing", credential.Label, credential.Status)
|
||||
}
|
||||
return credential, nil
|
||||
}
|
||||
|
||||
func (m *Model) credentialByID(id string) (domain.Credential, bool) {
|
||||
for _, credential := range m.credentials {
|
||||
if credential.ID == id {
|
||||
return credential, true
|
||||
}
|
||||
}
|
||||
return domain.Credential{}, false
|
||||
}
|
||||
|
||||
func (m *Model) mutationFormBlocked() bool {
|
||||
switch {
|
||||
case m.recoveryBlocked:
|
||||
m.toast, m.toastAt = "Crash recovery must succeed before mutations are enabled", time.Now()
|
||||
case m.busy:
|
||||
m.toast, m.toastAt = "An operation is already running", time.Now()
|
||||
case m.loading:
|
||||
m.toast, m.toastAt = "Loading the latest zone state", time.Now()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *Model) openRecordForm(editing bool) {
|
||||
newInput := func(placeholder string) textinput.Model {
|
||||
input := textinput.New()
|
||||
@@ -1383,12 +1727,14 @@ func (m *Model) isMutationKey(key string) bool {
|
||||
return true
|
||||
case "a":
|
||||
return m.screen == screenDashboard || m.screen == screenAccounts
|
||||
case "p":
|
||||
return m.screen == screenZones
|
||||
case "n":
|
||||
return m.screen == screenDNS || m.screen == screenCertificates
|
||||
case "i", "x", "u":
|
||||
return m.screen == screenCertificates
|
||||
case "d":
|
||||
return m.screen == screenDNS || m.screen == screenCertificates
|
||||
return m.screen == screenAccounts || m.screen == screenDNS || m.screen == screenCertificates
|
||||
case "e":
|
||||
return m.screen == screenDNS
|
||||
case "s", "m", "t", "v", "h":
|
||||
@@ -1493,8 +1839,25 @@ func (m *Model) updateOverlay(message tea.Msg) (tea.Model, tea.Cmd) {
|
||||
m.openCredentialForm()
|
||||
return m, textinput.Blink
|
||||
}
|
||||
m.busy = true
|
||||
return m, syncCmd(m.backend)
|
||||
switch selected - len(screens) {
|
||||
case 1:
|
||||
m.busy = true
|
||||
return m, syncCmd(m.backend)
|
||||
case 2:
|
||||
if m.screen != screenAccounts || len(m.filteredCredentials()) == 0 {
|
||||
m.toast, m.toastAt = "Select a connection in Accounts first", time.Now()
|
||||
return m, nil
|
||||
}
|
||||
m.openRemoveCredentialForm()
|
||||
return m, textinput.Blink
|
||||
case 3:
|
||||
if m.screen != screenZones || len(m.filteredZones()) == 0 {
|
||||
m.toast, m.toastAt = "Select a zone in Zones first", time.Now()
|
||||
return m, nil
|
||||
}
|
||||
m.openPreferredCredentialForm()
|
||||
return m, textinput.Blink
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
@@ -1737,6 +2100,12 @@ func (m *Model) resizeInputs() {
|
||||
for i := range m.credentialInputs {
|
||||
m.credentialInputs[i].SetWidth(width)
|
||||
}
|
||||
if m.removeCredential {
|
||||
m.removeCredentialInput.SetWidth(width)
|
||||
}
|
||||
for i := range m.preferCredentialInputs {
|
||||
m.preferCredentialInputs[i].SetWidth(width)
|
||||
}
|
||||
for i := range m.recordInputs {
|
||||
m.recordInputs[i].SetWidth(width)
|
||||
}
|
||||
@@ -1778,9 +2147,14 @@ func max(a, b int) int {
|
||||
}
|
||||
|
||||
func paletteCommands() []string {
|
||||
result := make([]string, 0, len(screens)+2)
|
||||
result := make([]string, 0, len(screens)+4)
|
||||
for _, item := range screens {
|
||||
result = append(result, "Go to "+item.name)
|
||||
}
|
||||
return append(result, "Add Cloudflare account", "Synchronize everything")
|
||||
return append(result,
|
||||
"Add Cloudflare account",
|
||||
"Synchronize everything",
|
||||
"Remove selected Cloudflare connection/token",
|
||||
"Set selected zone preferred connection",
|
||||
)
|
||||
}
|
||||
+278
-15
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/lipgloss/v2"
|
||||
|
||||
"github.com/MeghdadFadaee/domainops/internal/app"
|
||||
"github.com/MeghdadFadaee/domainops/internal/domain"
|
||||
@@ -713,6 +714,254 @@ func TestLoadingCommandPaletteRejectsMutationEntries(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveCredentialCapturesExactIDAndDisclosesAffectedRoutes(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenAccounts
|
||||
model.credentials = []domain.Credential{
|
||||
{ID: "credential-a", Label: "Primary", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-b", Label: "Retiring", Provider: domain.ProviderCloudflare, Kind: domain.CredentialAccountToken, AccountHint: "account-main", Status: domain.CredentialValid},
|
||||
}
|
||||
model.zones = []domain.Zone{
|
||||
{ID: "zone-a", Name: "example.com", PreferredCredentialID: "credential-b"},
|
||||
{ID: "zone-b", Name: "example.net", PreferredCredentialID: "credential-b"},
|
||||
}
|
||||
model.rowOffset = 1
|
||||
|
||||
_, blink := model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
|
||||
if blink == nil || !model.removeCredential || model.removeCredentialID != "credential-b" || model.removeCredentialInput.Value() != "" {
|
||||
t.Fatalf("remove form = open:%v id:%q input:%q cmd:%v", model.removeCredential, model.removeCredentialID, model.removeCredentialInput.Value(), blink != nil)
|
||||
}
|
||||
view := model.View().Content
|
||||
for _, expected := range []string{"Retiring", "credential-b", "account_token", "account-main", "2 preferred zone route", "example.com", "example.net", "reassigned"} {
|
||||
if !strings.Contains(view, expected) {
|
||||
t.Fatalf("remove form does not disclose %q: %q", expected, view)
|
||||
}
|
||||
}
|
||||
|
||||
// A refresh/reorder after opening must not redirect removal to the new row.
|
||||
_, _ = model.Update(loadMsg{credentials: []domain.Credential{
|
||||
{ID: "credential-b", Label: "Retiring", Provider: domain.ProviderCloudflare, Kind: domain.CredentialAccountToken, AccountHint: "account-main", Status: domain.CredentialValid},
|
||||
{ID: "credential-a", Label: "Primary", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
}, zones: model.zones})
|
||||
model.removeCredentialInput.SetValue("Retiring")
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd == nil || model.removeCredential || !model.busy {
|
||||
t.Fatalf("confirmed removal = cmd:%v open:%v busy:%v", cmd != nil, model.removeCredential, model.busy)
|
||||
}
|
||||
message, ok := cmd().(operationMsg)
|
||||
if !ok || !message.reload || message.err != nil {
|
||||
t.Fatalf("remove result = %#v", message)
|
||||
}
|
||||
if len(backend.deletedCredentials) != 1 || backend.deletedCredentials[0] != "credential-b" {
|
||||
t.Fatalf("deleted credential IDs = %v", backend.deletedCredentials)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveCredentialCancellationAndStaleConnectionAreSafe(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenAccounts
|
||||
model.credentials = []domain.Credential{{ID: "credential", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
|
||||
model.removeCredentialInput.SetValue("Production")
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
|
||||
if model.removeCredential || model.removeCredentialID != "" || model.removeCredentialExpected != "" || model.removeCredentialInput.Value() != "" {
|
||||
t.Fatalf("cancel retained remove state: open=%v id=%q label=%q input=%q", model.removeCredential, model.removeCredentialID, model.removeCredentialExpected, model.removeCredentialInput.Value())
|
||||
}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
|
||||
model.removeCredentialInput.SetValue("Production")
|
||||
model.credentials = nil
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd != nil || model.err == nil || len(backend.deletedCredentials) != 0 {
|
||||
t.Fatalf("stale remove mutated: cmd=%v err=%v calls=%v", cmd != nil, model.err, backend.deletedCredentials)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveCredentialRejectsChangedAffectedRoutes(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenAccounts
|
||||
model.credentials = []domain.Credential{{ID: "credential", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}}
|
||||
model.zones = []domain.Zone{{ID: "zone-a", Name: "example.com", PreferredCredentialID: "credential"}}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
|
||||
model.removeCredentialInput.SetValue("Production")
|
||||
model.zones = append(model.zones, domain.Zone{ID: "zone-b", Name: "example.net", PreferredCredentialID: "credential"})
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd != nil || model.err == nil || !strings.Contains(model.err.Error(), "affected zone routes changed") || len(backend.deletedCredentials) != 0 {
|
||||
t.Fatalf("changed route disclosure mutated: cmd=%v err=%v calls=%v", cmd != nil, model.err, backend.deletedCredentials)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveCredentialSurfacesFailClosedReplacementError(t *testing.T) {
|
||||
backend := &fakeBackend{deleteCredentialErr: errors.New("zone example.com has no proven replacement")}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenAccounts
|
||||
model.credentials = []domain.Credential{{ID: "credential", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'd', Text: "d"})
|
||||
model.removeCredentialInput.SetValue("Production")
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd == nil {
|
||||
t.Fatal("confirmed removal did not call backend")
|
||||
}
|
||||
_, reload := model.Update(cmd())
|
||||
if reload == nil || model.err == nil || !strings.Contains(model.err.Error(), "no proven replacement") {
|
||||
t.Fatalf("replacement failure = reload:%v err:%v", reload != nil, model.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredCredentialRejectsAmbiguousLabelAndInvalidCandidates(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
zone := domain.Zone{ID: "zone", Name: "example.com", Provider: domain.ProviderCloudflare}
|
||||
model.screen = screenZones
|
||||
model.zones = []domain.Zone{zone}
|
||||
model.credentials = []domain.Credential{
|
||||
{ID: "credential-a", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-b", Label: "production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-invalid", Label: "Invalid", Provider: domain.ProviderCloudflare, Status: domain.CredentialInvalid},
|
||||
{ID: "credential-other", Label: "Other", Provider: "other", Status: domain.CredentialValid},
|
||||
}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'p', Text: "p"})
|
||||
if model.preferCredentialInputs[0].Value() != "" || model.preferCredentialInputs[1].Value() != "" {
|
||||
t.Fatalf("preference confirmation was prefilled: %#v", model.preferCredentialInputs)
|
||||
}
|
||||
model.preferCredentialInputs[0].SetValue("Production")
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd != nil || model.preferCredentialFocus != 0 || model.err == nil || !strings.Contains(model.err.Error(), "ambiguous") {
|
||||
t.Fatalf("ambiguous label = cmd:%v focus:%d err:%v", cmd != nil, model.preferCredentialFocus, model.err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
value string
|
||||
want string
|
||||
}{{"credential-invalid", "invalid"}, {"credential-other", "provider"}} {
|
||||
model.preferCredentialInputs[0].SetValue(test.value)
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if model.err == nil || !strings.Contains(model.err.Error(), test.want) {
|
||||
t.Fatalf("selector %q error = %v, want %q", test.value, model.err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredCredentialCapturesIDAcrossRefreshAndCallsExactZone(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenZones
|
||||
model.zones = []domain.Zone{{ID: "zone-id", Name: "example.com", Provider: domain.ProviderCloudflare, PreferredCredentialID: "credential-old"}}
|
||||
model.credentials = []domain.Credential{
|
||||
{ID: "credential-old", Label: "Old", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-selected", Label: "Replacement", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'p', Text: "p"})
|
||||
model.preferCredentialInputs[0].SetValue("Replacement")
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if model.preferCredentialFocus != 1 || model.preferResolvedCredentialID != "credential-selected" {
|
||||
t.Fatalf("captured credential = focus:%d id:%q err:%v", model.preferCredentialFocus, model.preferResolvedCredentialID, model.err)
|
||||
}
|
||||
|
||||
// The label becomes ambiguous after capture. Final confirmation must retain
|
||||
// the immutable ID instead of resolving the label to a different row.
|
||||
_, _ = model.Update(loadMsg{zones: model.zones, credentials: []domain.Credential{
|
||||
{ID: "credential-new", Label: "Replacement", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-selected", Label: "Replacement", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
{ID: "credential-old", Label: "Old", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid},
|
||||
}})
|
||||
model.preferCredentialInputs[1].SetValue("example.com")
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd == nil || model.preferCredential || !model.busy {
|
||||
t.Fatalf("preference submit = cmd:%v open:%v busy:%v err:%v", cmd != nil, model.preferCredential, model.busy, model.err)
|
||||
}
|
||||
message, ok := cmd().(operationMsg)
|
||||
if !ok || !message.reload || message.err != nil {
|
||||
t.Fatalf("preference result = %#v", message)
|
||||
}
|
||||
if fmt.Sprint(backend.preferredZones) != "[zone-id]" || fmt.Sprint(backend.preferredCredentials) != "[credential-selected]" {
|
||||
t.Fatalf("preferred calls = zones:%v credentials:%v", backend.preferredZones, backend.preferredCredentials)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredCredentialFormFitsMinimumTerminalAndShowsRoutingIdentity(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
_, _ = model.Update(tea.WindowSizeMsg{Width: 64, Height: 18})
|
||||
model.screen = screenZones
|
||||
model.accounts = []domain.RemoteAccount{{ID: "account-id", Name: "Primary"}}
|
||||
model.zones = []domain.Zone{{ID: "zone-id", Name: "example.com", Provider: domain.ProviderCloudflare, AccountID: "account-id", PreferredCredentialID: "credential-current"}}
|
||||
model.credentials = []domain.Credential{
|
||||
{ID: "credential-current", Label: "Current", Provider: domain.ProviderCloudflare, Kind: domain.CredentialUserToken, Status: domain.CredentialValid, Capabilities: []string{"dns:read", "dns:write"}},
|
||||
{ID: "credential-next", Label: "Next", Provider: domain.ProviderCloudflare, Kind: domain.CredentialAccountToken, AccountHint: "account-id", Status: domain.CredentialValid, Capabilities: []string{"dns:read"}},
|
||||
}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'p', Text: "p"})
|
||||
view := model.View().Content
|
||||
if height := lipgloss.Height(view); height > 18 {
|
||||
t.Fatalf("minimum-terminal preference modal height = %d\n%s", height, view)
|
||||
}
|
||||
for _, expected := range []string{"example.com", "zone-id", "Primary", "account-id", "credential-current", "Current", "current"} {
|
||||
if !strings.Contains(view, expected) {
|
||||
t.Fatalf("preference form does not show %q: %q", expected, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreferredCredentialCancellationAndStaleRouteAreSafe(t *testing.T) {
|
||||
backend := &fakeBackend{}
|
||||
model := New(backend, Options{})
|
||||
model.screen = screenZones
|
||||
model.zones = []domain.Zone{{ID: "zone", Name: "example.com", Provider: domain.ProviderCloudflare, PreferredCredentialID: "old"}}
|
||||
model.credentials = []domain.Credential{{ID: "new", Label: "New", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'p', Text: "p"})
|
||||
model.preferCredentialInputs[0].SetValue("new")
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
|
||||
if model.preferCredential || model.preferZoneID != "" || model.preferResolvedCredentialID != "" || len(model.preferCredentialInputs) != 2 || model.preferCredentialInputs[0].Value() != "" {
|
||||
t.Fatalf("cancel retained preference state: %#v", model)
|
||||
}
|
||||
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: 'p', Text: "p"})
|
||||
model.preferCredentialInputs[0].SetValue("new")
|
||||
_, _ = model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
model.zones[0].PreferredCredentialID = "changed-elsewhere"
|
||||
model.preferCredentialInputs[1].SetValue("example.com")
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
|
||||
if cmd != nil || model.err == nil || !strings.Contains(model.err.Error(), "route changed") || len(backend.preferredZones) != 0 {
|
||||
t.Fatalf("stale route mutated: cmd=%v err=%v calls=%v", cmd != nil, model.err, backend.preferredZones)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccountAndZoneMutationsRespectRecoveryBusyAndLoadingGuards(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
screen screen
|
||||
key rune
|
||||
blocked func(*Model)
|
||||
}{
|
||||
{"remove recovery", screenAccounts, 'd', func(m *Model) { m.recoveryBlocked = true }},
|
||||
{"remove busy", screenAccounts, 'd', func(m *Model) { m.busy = true }},
|
||||
{"remove loading", screenAccounts, 'd', func(m *Model) { m.loading = true }},
|
||||
{"prefer recovery", screenZones, 'p', func(m *Model) { m.recoveryBlocked = true }},
|
||||
{"prefer busy", screenZones, 'p', func(m *Model) { m.busy = true }},
|
||||
{"prefer loading", screenZones, 'p', func(m *Model) { m.loading = true }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
model := New(&fakeBackend{}, Options{})
|
||||
model.screen = test.screen
|
||||
model.credentials = []domain.Credential{{ID: "credential", Label: "Production", Provider: domain.ProviderCloudflare, Status: domain.CredentialValid}}
|
||||
model.zones = []domain.Zone{{ID: "zone", Name: "example.com", Provider: domain.ProviderCloudflare}}
|
||||
test.blocked(model)
|
||||
_, cmd := model.Update(tea.KeyPressMsg{Code: test.key, Text: string(test.key)})
|
||||
if cmd != nil || model.removeCredential || model.preferCredential || model.toast == "" {
|
||||
t.Fatalf("blocked mutation = cmd:%v remove:%v prefer:%v toast:%q", cmd != nil, model.removeCredential, model.preferCredential, model.toast)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirstRunVaultRequiresConfirmation(t *testing.T) {
|
||||
backend := &fakeBackend{locked: true}
|
||||
model := New(backend, Options{FirstRun: true})
|
||||
@@ -754,21 +1003,26 @@ func TestExistingVaultAcceptsLegacyShortPassword(t *testing.T) {
|
||||
}
|
||||
|
||||
type fakeBackend struct {
|
||||
locked bool
|
||||
unlockCalls int
|
||||
unlockNilCalls int
|
||||
unlockErr error
|
||||
dnsZones []string
|
||||
zones []domain.Zone
|
||||
deleteCalls int
|
||||
tlsSettings map[string]domain.EdgeTLSSettings
|
||||
tlsErr error
|
||||
tlsZones []string
|
||||
updateTLSZones []string
|
||||
updateTLSDrafts []domain.EdgeTLSSettings
|
||||
issueRequests []app.IssueZonesRequest
|
||||
revokeLineages []string
|
||||
revokeConfirmations []string
|
||||
locked bool
|
||||
unlockCalls int
|
||||
unlockNilCalls int
|
||||
unlockErr error
|
||||
dnsZones []string
|
||||
zones []domain.Zone
|
||||
deleteCalls int
|
||||
deletedCredentials []string
|
||||
deleteCredentialErr error
|
||||
preferredZones []string
|
||||
preferredCredentials []string
|
||||
preferredCredentialErr error
|
||||
tlsSettings map[string]domain.EdgeTLSSettings
|
||||
tlsErr error
|
||||
tlsZones []string
|
||||
updateTLSZones []string
|
||||
updateTLSDrafts []domain.EdgeTLSSettings
|
||||
issueRequests []app.IssueZonesRequest
|
||||
revokeLineages []string
|
||||
revokeConfirmations []string
|
||||
}
|
||||
|
||||
func (f *fakeBackend) VaultLocked() bool { return f.locked }
|
||||
@@ -804,6 +1058,15 @@ func (f *fakeBackend) Audit(context.Context, int) ([]domain.AuditEvent, error) {
|
||||
func (f *fakeBackend) AddCloudflareCredential(context.Context, app.AddCredentialInput) (domain.Credential, error) {
|
||||
return domain.Credential{}, nil
|
||||
}
|
||||
func (f *fakeBackend) DeleteCredential(_ context.Context, credentialID string) error {
|
||||
f.deletedCredentials = append(f.deletedCredentials, credentialID)
|
||||
return f.deleteCredentialErr
|
||||
}
|
||||
func (f *fakeBackend) SetZonePreferredCredential(_ context.Context, zoneID, credentialID string) (domain.Zone, error) {
|
||||
f.preferredZones = append(f.preferredZones, zoneID)
|
||||
f.preferredCredentials = append(f.preferredCredentials, credentialID)
|
||||
return domain.Zone{ID: zoneID, PreferredCredentialID: credentialID}, f.preferredCredentialErr
|
||||
}
|
||||
func (f *fakeBackend) SyncAll(context.Context) ([]domain.Job, error) { return nil, nil }
|
||||
func (f *fakeBackend) CreateDNSRecord(context.Context, string, domain.DNSRecord) (domain.DNSRecord, error) {
|
||||
return domain.DNSRecord{}, nil
|
||||
|
||||
+133
-4
@@ -29,6 +29,12 @@ func (m *Model) render() string {
|
||||
if m.addCredential {
|
||||
return m.renderCredentialForm()
|
||||
}
|
||||
if m.removeCredential {
|
||||
return m.renderRemoveCredentialForm()
|
||||
}
|
||||
if m.preferCredential {
|
||||
return m.renderPreferredCredentialForm()
|
||||
}
|
||||
if m.editRecord {
|
||||
return m.renderRecordForm()
|
||||
}
|
||||
@@ -87,6 +93,12 @@ func (m *Model) renderHeader() string {
|
||||
func (m *Model) renderFooter() string {
|
||||
left := m.theme.key.Render("?") + " help " + m.theme.key.Render("Ctrl+K") + " commands " + m.theme.key.Render("/") + " filter"
|
||||
right := m.theme.key.Render("r") + " sync " + m.theme.key.Render("q") + " quit"
|
||||
switch m.screen {
|
||||
case screenAccounts:
|
||||
right = m.theme.key.Render("a") + " add " + m.theme.key.Render("d") + " remove " + m.theme.key.Render("q") + " quit"
|
||||
case screenZones:
|
||||
right = m.theme.key.Render("p") + " set route " + m.theme.key.Render("Enter") + " DNS " + m.theme.key.Render("q") + " quit"
|
||||
}
|
||||
if m.recoveryBlocked {
|
||||
right = m.theme.key.Render("R") + " retry recovery " + m.theme.key.Render("q") + " quit"
|
||||
}
|
||||
@@ -221,7 +233,7 @@ func (m *Model) renderAccounts(width, height int) string {
|
||||
if len(values) == 0 {
|
||||
return m.emptyState("No Cloudflare accounts", "Press a to add a scoped API token.", width, height)
|
||||
}
|
||||
header := row(width, []cell{{"LABEL", 28}, {"TOKEN", 18}, {"STATUS", 14}, {"CAPABILITIES", 40}})
|
||||
header := row(width, []cell{{"LABEL", 24}, {"CREDENTIAL ID", 28}, {"TOKEN", 16}, {"STATUS", 12}, {"CAPABILITIES", 30}})
|
||||
rows := []string{m.theme.mutedText.Render(header)}
|
||||
reserved := 0
|
||||
if len(m.accounts) > 0 {
|
||||
@@ -232,7 +244,7 @@ func (m *Model) renderAccounts(width, height int) string {
|
||||
for i := start; i < len(values) && i < start+limit; i++ {
|
||||
value := values[i]
|
||||
status := string(value.Status)
|
||||
line := row(width, []cell{{value.Label, 28}, {string(value.Kind), 18}, {status, 14}, {strings.Join(value.Capabilities, ", "), 40}})
|
||||
line := row(width, []cell{{value.Label, 24}, {value.ID, 28}, {string(value.Kind), 16}, {status, 12}, {strings.Join(value.Capabilities, ", "), 30}})
|
||||
if i == m.rowOffset {
|
||||
line = m.theme.selected.Width(width - 2).Render(line)
|
||||
}
|
||||
@@ -245,7 +257,7 @@ func (m *Model) renderAccounts(width, height int) string {
|
||||
}
|
||||
rows = append(rows, "", m.theme.panelTitle.Render(fmt.Sprintf("REMOTE ACCOUNTS · %d", len(m.accounts))), m.theme.mutedText.Render(truncate(strings.Join(names, " · "), max(1, width-6))))
|
||||
}
|
||||
return m.panel("CLOUDFLARE CONNECTIONS · a add · r sync", strings.Join(rows, "\n"), width, height)
|
||||
return m.panel("CLOUDFLARE CONNECTIONS · a add · d safely remove · r sync", strings.Join(rows, "\n"), width, height)
|
||||
}
|
||||
|
||||
func (m *Model) renderZones(width, height int) string {
|
||||
@@ -265,7 +277,7 @@ func (m *Model) renderZones(width, height int) string {
|
||||
}
|
||||
rows = append(rows, line)
|
||||
}
|
||||
return m.panel("ZONES · Enter open DNS · j/k select", strings.Join(rows, "\n"), width, height)
|
||||
return m.panel("ZONES · Enter open DNS · p set preferred connection · j/k select", strings.Join(rows, "\n"), width, height)
|
||||
}
|
||||
|
||||
func (m *Model) accountLabel(id string) string {
|
||||
@@ -527,6 +539,122 @@ func (m *Model) renderCredentialForm() string {
|
||||
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
|
||||
}
|
||||
|
||||
func (m *Model) renderRemoveCredentialForm() string {
|
||||
contentWidth := max(20, min(70, m.width-16))
|
||||
affected := "No currently preferred zone routes use this connection."
|
||||
if len(m.removeCredentialZoneIDs) > 0 {
|
||||
names := m.removeCredentialZoneNames
|
||||
shown := names
|
||||
if len(shown) > 4 {
|
||||
shown = shown[:4]
|
||||
}
|
||||
affected = fmt.Sprintf("%d preferred zone route(s): %s", len(names), strings.Join(shown, ", "))
|
||||
if len(names) > len(shown) {
|
||||
affected += fmt.Sprintf(" … and %d more", len(names)-len(shown))
|
||||
}
|
||||
}
|
||||
hint := m.removeCredentialAccountHint
|
||||
if hint == "" {
|
||||
hint = "all discovered accounts"
|
||||
}
|
||||
lines := []string{
|
||||
m.theme.brand.Render("REMOVE CLOUDFLARE CONNECTION / TOKEN"),
|
||||
m.theme.mutedText.Render(truncate("Connection: "+m.removeCredentialExpected+" · "+m.removeCredentialID, contentWidth)),
|
||||
m.theme.mutedText.Render(truncate(fmt.Sprintf("Token: %s · account scope: %s", m.removeCredentialKind, hint), contentWidth)),
|
||||
m.theme.mutedText.Render(truncate(affected, contentWidth)),
|
||||
m.theme.statusWarn.Render("Routes may be reassigned after live verification."),
|
||||
m.theme.statusWarn.Render("Fails closed unless every route has a proven replacement."),
|
||||
m.theme.panelTitle.Render("Exact connection label"),
|
||||
m.removeCredentialInput.View(),
|
||||
}
|
||||
if m.err != nil {
|
||||
lines = append(lines, m.theme.statusBad.Render(truncate("! "+m.err.Error(), contentWidth)))
|
||||
}
|
||||
lines = append(lines, m.theme.mutedText.Render("Enter to remove · Esc to cancel"))
|
||||
modal := m.theme.modal.Width(min(78, m.width-8)).Render(strings.Join(lines, "\n"))
|
||||
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
|
||||
}
|
||||
|
||||
func (m *Model) renderPreferredCredentialForm() string {
|
||||
contentWidth := max(20, m.width-16)
|
||||
current := "automatic / none"
|
||||
if m.preferOriginalCredentialID != "" {
|
||||
current = m.credentialLabel(m.preferOriginalCredentialID) + " · " + m.preferOriginalCredentialID
|
||||
}
|
||||
account := m.accountLabel(m.preferZoneAccountID)
|
||||
if account == "" {
|
||||
account = "unknown"
|
||||
}
|
||||
selectorLabel := m.theme.mutedText.Render("Credential ID or unique label")
|
||||
confirmLabel := m.theme.mutedText.Render("Confirm exact zone name")
|
||||
if m.preferCredentialFocus == 0 {
|
||||
selectorLabel = m.theme.panelTitle.Render("Credential ID or unique label")
|
||||
} else {
|
||||
confirmLabel = m.theme.panelTitle.Render("Confirm exact zone name")
|
||||
}
|
||||
lines := []string{
|
||||
m.theme.brand.Render("SET PREFERRED ZONE CONNECTION"),
|
||||
m.theme.mutedText.Render(truncate("Zone: "+m.preferZoneExpectedName+" · "+m.preferZoneID, contentWidth)),
|
||||
m.theme.mutedText.Render(truncate("Account: "+account+" · "+m.preferZoneAccountID, contentWidth)),
|
||||
m.theme.mutedText.Render(truncate("Current route: "+current, contentWidth)),
|
||||
selectorLabel,
|
||||
m.preferCredentialInputs[0].View(),
|
||||
confirmLabel,
|
||||
m.preferCredentialInputs[1].View(),
|
||||
m.theme.mutedText.Render("Connections · DNS read verified on apply:"),
|
||||
}
|
||||
validCandidates := 0
|
||||
for _, credential := range m.credentials {
|
||||
if credential.Provider == m.preferZoneProvider && credential.Status == domain.CredentialValid {
|
||||
validCandidates++
|
||||
}
|
||||
}
|
||||
candidateLimit := max(1, min(6, (m.height-16)/2))
|
||||
shown := 0
|
||||
for _, credential := range m.credentials {
|
||||
if credential.Provider != m.preferZoneProvider || credential.Status != domain.CredentialValid {
|
||||
continue
|
||||
}
|
||||
marker := " "
|
||||
if credential.ID == m.preferOriginalCredentialID {
|
||||
marker = "*"
|
||||
}
|
||||
hint := credential.AccountHint
|
||||
if hint == "" {
|
||||
hint = "all discovered accounts"
|
||||
}
|
||||
writeState := "dns:write observed before"
|
||||
if !containsString(credential.Capabilities, "dns:write") {
|
||||
writeState = "WRITE UNPROVEN"
|
||||
}
|
||||
labelWidth := max(1, contentWidth-len(credential.ID)-5)
|
||||
candidate := fmt.Sprintf("%s %s · %s", marker, credential.ID, truncate(credential.Label, labelWidth))
|
||||
details := fmt.Sprintf(" %s · %s · %s · %s", writeState, credential.Kind, hint, strings.Join(credential.Capabilities, ","))
|
||||
lines = append(lines, m.theme.mutedText.Render(truncate(candidate, contentWidth)))
|
||||
if writeState == "WRITE UNPROVEN" {
|
||||
lines = append(lines, m.theme.statusWarn.Render(truncate(details, contentWidth)))
|
||||
} else {
|
||||
lines = append(lines, m.theme.mutedText.Render(truncate(details, contentWidth)))
|
||||
}
|
||||
shown++
|
||||
if shown == candidateLimit {
|
||||
break
|
||||
}
|
||||
}
|
||||
if shown == 0 {
|
||||
lines = append(lines, m.theme.statusWarn.Render(" No valid synchronized connection matches this zone provider."))
|
||||
} else if validCandidates > shown {
|
||||
lines = append(lines, m.theme.mutedText.Render(truncate(fmt.Sprintf(" … and %d more; full IDs are visible in Accounts", validCandidates-shown), contentWidth)))
|
||||
}
|
||||
lines = append(lines, m.theme.mutedText.Render("* current · write proven only by a real mutation"))
|
||||
if m.err != nil {
|
||||
lines = append(lines, m.theme.statusBad.Render(truncate("! "+m.err.Error(), contentWidth)))
|
||||
}
|
||||
lines = append(lines, m.theme.mutedText.Render("Tab move · Enter verify/apply · Esc cancel"))
|
||||
modal := m.theme.modal.Width(min(84, m.width-8)).Render(strings.Join(lines, "\n"))
|
||||
return m.theme.app.Width(m.width).Height(m.height).Render(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, modal))
|
||||
}
|
||||
|
||||
func (m *Model) renderRecordForm() string {
|
||||
labels := []string{"Record type", "Name", "Content", "TTL", "Priority"}
|
||||
title := "CREATE DNS RECORD"
|
||||
@@ -661,6 +789,7 @@ func (m *Model) renderHelp() string {
|
||||
m.theme.key.Render("1…7") + " Navigate sections", m.theme.key.Render("j / k") + " Move selection",
|
||||
m.theme.key.Render("/") + " Filter current view", m.theme.key.Render("Ctrl+K") + " Command palette",
|
||||
m.theme.key.Render("r") + " Synchronize", m.theme.key.Render("a") + " Add Cloudflare connection",
|
||||
m.theme.key.Render("d") + " Safely remove selected connection (Accounts)", m.theme.key.Render("p") + " Set preferred zone connection (Zones)",
|
||||
m.theme.key.Render("n / e / d") + " New, edit, delete DNS record", m.theme.key.Render("?") + " Close this help",
|
||||
m.theme.key.Render("n / u / i / x / d") + " Issue, renew due, import, export, revoke certificate",
|
||||
"", m.theme.mutedText.Render("All operations are keyboard-accessible and safe over SSH."),
|
||||
|
||||
Reference in new issue
Block a user