github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/trust/common.go (about)

     1  package trust
     2  
     3  import (
     4  	"context"
     5  	"encoding/hex"
     6  	"fmt"
     7  	"sort"
     8  	"strings"
     9  
    10  	"github.com/docker/cli/cli/command"
    11  	"github.com/docker/cli/cli/command/image"
    12  	"github.com/docker/cli/cli/trust"
    13  	"github.com/fvbommel/sortorder"
    14  	"github.com/sirupsen/logrus"
    15  	"github.com/theupdateframework/notary"
    16  	"github.com/theupdateframework/notary/client"
    17  	"github.com/theupdateframework/notary/tuf/data"
    18  )
    19  
    20  // trustTagKey represents a unique signed tag and hex-encoded hash pair
    21  type trustTagKey struct {
    22  	SignedTag string
    23  	Digest    string
    24  }
    25  
    26  // trustTagRow encodes all human-consumable information for a signed tag, including signers
    27  type trustTagRow struct {
    28  	trustTagKey
    29  	Signers []string
    30  }
    31  
    32  // trustRepo represents consumable information about a trusted repository
    33  type trustRepo struct {
    34  	Name               string
    35  	SignedTags         []trustTagRow
    36  	Signers            []trustSigner
    37  	AdministrativeKeys []trustSigner
    38  }
    39  
    40  // trustSigner represents a trusted signer in a trusted repository
    41  // a signer is defined by a name and list of trustKeys
    42  type trustSigner struct {
    43  	Name string     `json:",omitempty"`
    44  	Keys []trustKey `json:",omitempty"`
    45  }
    46  
    47  // trustKey contains information about trusted keys
    48  type trustKey struct {
    49  	ID string `json:",omitempty"`
    50  }
    51  
    52  // lookupTrustInfo returns processed signature and role information about a notary repository.
    53  // This information is to be pretty printed or serialized into a machine-readable format.
    54  func lookupTrustInfo(ctx context.Context, cli command.Cli, remote string) ([]trustTagRow, []client.RoleWithSignatures, []data.Role, error) {
    55  	imgRefAndAuth, err := trust.GetImageReferencesAndAuth(ctx, image.AuthResolver(cli), remote)
    56  	if err != nil {
    57  		return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err
    58  	}
    59  	tag := imgRefAndAuth.Tag()
    60  	notaryRepo, err := cli.NotaryClient(imgRefAndAuth, trust.ActionsPullOnly)
    61  	if err != nil {
    62  		return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, trust.NotaryError(imgRefAndAuth.Reference().Name(), err)
    63  	}
    64  
    65  	if err = clearChangeList(notaryRepo); err != nil {
    66  		return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, err
    67  	}
    68  	defer clearChangeList(notaryRepo)
    69  
    70  	// Retrieve all released signatures, match them, and pretty print them
    71  	allSignedTargets, err := notaryRepo.GetAllTargetMetadataByName(tag)
    72  	if err != nil {
    73  		logrus.Debug(trust.NotaryError(remote, err))
    74  		// print an empty table if we don't have signed targets, but have an initialized notary repo
    75  		if _, ok := err.(client.ErrNoSuchTarget); !ok {
    76  			return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("no signatures or cannot access %s", remote)
    77  		}
    78  	}
    79  	signatureRows := matchReleasedSignatures(allSignedTargets)
    80  
    81  	// get the administrative roles
    82  	adminRolesWithSigs, err := notaryRepo.ListRoles()
    83  	if err != nil {
    84  		return []trustTagRow{}, []client.RoleWithSignatures{}, []data.Role{}, fmt.Errorf("no signers for %s", remote)
    85  	}
    86  
    87  	// get delegation roles with the canonical key IDs
    88  	delegationRoles, err := notaryRepo.GetDelegationRoles()
    89  	if err != nil {
    90  		logrus.Debugf("no delegation roles found, or error fetching them for %s: %v", remote, err)
    91  	}
    92  
    93  	return signatureRows, adminRolesWithSigs, delegationRoles, nil
    94  }
    95  
    96  func formatAdminRole(roleWithSigs client.RoleWithSignatures) string {
    97  	adminKeyList := roleWithSigs.KeyIDs
    98  	sort.Strings(adminKeyList)
    99  
   100  	var role string
   101  	switch roleWithSigs.Name {
   102  	case data.CanonicalTargetsRole:
   103  		role = "Repository Key"
   104  	case data.CanonicalRootRole:
   105  		role = "Root Key"
   106  	default:
   107  		return ""
   108  	}
   109  	return fmt.Sprintf("%s:\t%s\n", role, strings.Join(adminKeyList, ", "))
   110  }
   111  
   112  func getDelegationRoleToKeyMap(rawDelegationRoles []data.Role) map[string][]string {
   113  	signerRoleToKeyIDs := make(map[string][]string)
   114  	for _, delRole := range rawDelegationRoles {
   115  		switch delRole.Name {
   116  		case trust.ReleasesRole, data.CanonicalRootRole, data.CanonicalSnapshotRole, data.CanonicalTargetsRole, data.CanonicalTimestampRole:
   117  			continue
   118  		default:
   119  			signerRoleToKeyIDs[notaryRoleToSigner(delRole.Name)] = delRole.KeyIDs
   120  		}
   121  	}
   122  	return signerRoleToKeyIDs
   123  }
   124  
   125  // aggregate all signers for a "released" hash+tagname pair. To be "released," the tag must have been
   126  // signed into the "targets" or "targets/releases" role. Output is sorted by tag name
   127  func matchReleasedSignatures(allTargets []client.TargetSignedStruct) []trustTagRow {
   128  	signatureRows := []trustTagRow{}
   129  	// do a first pass to get filter on tags signed into "targets" or "targets/releases"
   130  	releasedTargetRows := map[trustTagKey][]string{}
   131  	for _, tgt := range allTargets {
   132  		if isReleasedTarget(tgt.Role.Name) {
   133  			releasedKey := trustTagKey{tgt.Target.Name, hex.EncodeToString(tgt.Target.Hashes[notary.SHA256])}
   134  			releasedTargetRows[releasedKey] = []string{}
   135  		}
   136  	}
   137  
   138  	// now fill out all signers on released keys
   139  	for _, tgt := range allTargets {
   140  		targetKey := trustTagKey{tgt.Target.Name, hex.EncodeToString(tgt.Target.Hashes[notary.SHA256])}
   141  		// only considered released targets
   142  		if _, ok := releasedTargetRows[targetKey]; ok && !isReleasedTarget(tgt.Role.Name) {
   143  			releasedTargetRows[targetKey] = append(releasedTargetRows[targetKey], notaryRoleToSigner(tgt.Role.Name))
   144  		}
   145  	}
   146  
   147  	// compile the final output as a sorted slice
   148  	for targetKey, signers := range releasedTargetRows {
   149  		signatureRows = append(signatureRows, trustTagRow{targetKey, signers})
   150  	}
   151  	sort.Slice(signatureRows, func(i, j int) bool {
   152  		return sortorder.NaturalLess(signatureRows[i].SignedTag, signatureRows[j].SignedTag)
   153  	})
   154  	return signatureRows
   155  }