|
| 1 | +// Copyright AGNTCY Contributors (https://github.com/agntcy) |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +package v1 |
| 5 | + |
| 6 | +import ( |
| 7 | + "regexp" |
| 8 | + "slices" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "google.golang.org/protobuf/types/known/structpb" |
| 12 | +) |
| 13 | + |
| 14 | +// DefaultOASFSchemaURL is the OASF schema server whose extensions are accepted |
| 15 | +// when no other schema servers are configured. |
| 16 | +const DefaultOASFSchemaURL = "https://schema.oasf.outshift.com" |
| 17 | + |
| 18 | +// DiscoveryInstanceAnnotation is the annotation in which a discovery instance records its ID |
| 19 | +// on every workload it writes. |
| 20 | +const DiscoveryInstanceAnnotation = "org.agntcy/discovery-instance" |
| 21 | + |
| 22 | +const ( |
| 23 | + discoveryObjectPath = "/objects/discovery" |
| 24 | + identityObjectPath = "/objects/identity" |
| 25 | +) |
| 26 | + |
| 27 | +// OASFClass is an OASF skill or domain reference. |
| 28 | +type OASFClass struct { |
| 29 | + Name string |
| 30 | + ID uint32 |
| 31 | +} |
| 32 | + |
| 33 | +// AgentInfo is what a workload says about the agent it runs. |
| 34 | +// |
| 35 | +// It is read from the workload's A2A card (services.a2a): the card's name, and the OASF |
| 36 | +// discovery and identity extensions served by an accepted schema server. Whatever the card |
| 37 | +// does not provide is read from the OASF record the workload references (services.oasf). |
| 38 | +// The values are claims made by whoever deployed the workload; nothing here is verified. |
| 39 | +type AgentInfo struct { |
| 40 | + // Name is the agent's name. |
| 41 | + Name string |
| 42 | + // SchemaVersion is the OASF schema version of Skills and Domains. |
| 43 | + SchemaVersion string |
| 44 | + // Skills are the agent's OASF skills. |
| 45 | + Skills []OASFClass |
| 46 | + // Domains are the agent's OASF domains. |
| 47 | + Domains []OASFClass |
| 48 | + // Authors are the agent's authors, e.g. the DID of the human vouching for it. |
| 49 | + Authors []string |
| 50 | +} |
| 51 | + |
| 52 | +// AgentInfo returns what the workload says about the agent it runs. |
| 53 | +// acceptedSchemaURLs lists the OASF schema servers whose extensions are read from the card; |
| 54 | +// when empty, only DefaultOASFSchemaURL is accepted. |
| 55 | +func (x *Workload) AgentInfo(acceptedSchemaURLs []string) AgentInfo { |
| 56 | + if len(acceptedSchemaURLs) == 0 { |
| 57 | + acceptedSchemaURLs = []string{DefaultOASFSchemaURL} |
| 58 | + } |
| 59 | + |
| 60 | + card := x.GetServices().GetA2A().GetFields() |
| 61 | + record := x.GetServices().GetOasf().GetFields()["record"].GetStructValue().GetFields() |
| 62 | + |
| 63 | + var info AgentInfo |
| 64 | + |
| 65 | + info.Name = card["name"].GetStringValue() |
| 66 | + if info.Name == "" { |
| 67 | + info.Name = record["name"].GetStringValue() |
| 68 | + } |
| 69 | + |
| 70 | + // Each value comes from the record unless the card's discovery extension provides it, |
| 71 | + // so an extension that leaves out a field (domains are optional) keeps the record's. |
| 72 | + info.SchemaVersion = record["schema_version"].GetStringValue() |
| 73 | + info.Skills = classes(record["skills"]) |
| 74 | + info.Domains = classes(record["domains"]) |
| 75 | + |
| 76 | + if discovery := cardExtension(card, discoveryObjectPath, acceptedSchemaURLs); discovery != nil { |
| 77 | + if version := discovery["schema_version"].GetStringValue(); version != "" { |
| 78 | + info.SchemaVersion = version |
| 79 | + } |
| 80 | + |
| 81 | + if skills := classes(discovery["skills"]); len(skills) > 0 { |
| 82 | + info.Skills = skills |
| 83 | + } |
| 84 | + |
| 85 | + if domains := classes(discovery["domains"]); len(domains) > 0 { |
| 86 | + info.Domains = domains |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if identity := cardExtension(card, identityObjectPath, acceptedSchemaURLs); identity != nil { |
| 91 | + if human := identity["human_did"].GetStringValue(); human != "" { |
| 92 | + info.Authors = []string{human} |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + if len(info.Authors) == 0 { |
| 97 | + for _, author := range record["authors"].GetListValue().GetValues() { |
| 98 | + if s := author.GetStringValue(); s != "" { |
| 99 | + info.Authors = append(info.Authors, s) |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + return info |
| 105 | +} |
| 106 | + |
| 107 | +// FilterOptions holds what MatchesFilters needs besides the request itself. |
| 108 | +type FilterOptions struct { |
| 109 | + // AcceptedSchemaURLs is passed to AgentInfo. |
| 110 | + AcceptedSchemaURLs []string |
| 111 | + // ReachableFrom is the workload named by the request's reachable_from_workload_id, |
| 112 | + // looked up by the caller. When the request sets that field and ReachableFrom is nil |
| 113 | + // or has another ID, no workload matches. |
| 114 | + ReachableFrom *Workload |
| 115 | +} |
| 116 | + |
| 117 | +// MatchesFilters reports whether the workload matches every filter of req, as documented |
| 118 | +// on ListWorkloadsRequest. |
| 119 | +func (x *Workload) MatchesFilters(req *ListWorkloadsRequest, opts FilterOptions) bool { |
| 120 | + return x.matchesRuntimeFilters(req, opts) && x.matchesAgentFilters(req, opts) |
| 121 | +} |
| 122 | + |
| 123 | +// matchesRuntimeFilters evaluates the filters on the workload itself: labels, runtime type, |
| 124 | +// reachability and locator protocols. |
| 125 | +func (x *Workload) matchesRuntimeFilters(req *ListWorkloadsRequest, opts FilterOptions) bool { |
| 126 | + if !x.matchesLabels(req.GetLabels()) { |
| 127 | + return false |
| 128 | + } |
| 129 | + |
| 130 | + if len(req.GetRuntimeTypes()) > 0 && !containsFold(req.GetRuntimeTypes(), x.GetRuntime()) { |
| 131 | + return false |
| 132 | + } |
| 133 | + |
| 134 | + if req.ReachableFromWorkloadId != nil && !x.reachableFrom(req.GetReachableFromWorkloadId(), opts.ReachableFrom) { |
| 135 | + return false |
| 136 | + } |
| 137 | + |
| 138 | + return len(req.GetLocatorProtocols()) == 0 || x.hasLocatorProtocol(req.GetLocatorProtocols()) |
| 139 | +} |
| 140 | + |
| 141 | +// matchesAgentFilters evaluates the filters on the agent the workload runs: names, skills, |
| 142 | +// domains, authors and schema versions. |
| 143 | +func (x *Workload) matchesAgentFilters(req *ListWorkloadsRequest, opts FilterOptions) bool { |
| 144 | + if len(req.GetNames()) == 0 && len(req.GetSkills()) == 0 && len(req.GetDomains()) == 0 && |
| 145 | + len(req.GetAuthors()) == 0 && len(req.GetSchemaVersions()) == 0 { |
| 146 | + return true |
| 147 | + } |
| 148 | + |
| 149 | + info := x.AgentInfo(opts.AcceptedSchemaURLs) |
| 150 | + |
| 151 | + return matchesAny(req.GetNames(), []string{info.Name}) && |
| 152 | + matchesAny(req.GetSkills(), classNames(info.Skills)) && |
| 153 | + matchesAny(req.GetDomains(), classNames(info.Domains)) && |
| 154 | + matchesAny(req.GetAuthors(), info.Authors) && |
| 155 | + matchesAny(req.GetSchemaVersions(), []string{info.SchemaVersion}) |
| 156 | +} |
| 157 | + |
| 158 | +// matchesLabels requires every label to be present with a value matching its pattern: |
| 159 | +// a regular expression matched anywhere in the value, or the exact value when the pattern |
| 160 | +// is not a valid regular expression. |
| 161 | +func (x *Workload) matchesLabels(filters map[string]string) bool { |
| 162 | + for key, pattern := range filters { |
| 163 | + value, exists := x.GetLabels()[key] |
| 164 | + if !exists { |
| 165 | + return false |
| 166 | + } |
| 167 | + |
| 168 | + matched, err := regexp.MatchString(pattern, value) |
| 169 | + if err != nil { |
| 170 | + matched = value == pattern |
| 171 | + } |
| 172 | + |
| 173 | + if !matched { |
| 174 | + return false |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + return true |
| 179 | +} |
| 180 | + |
| 181 | +// reachableFrom reports whether the workload shares an isolation group with from, |
| 182 | +// the workload with ID fromID. A workload is not reachable from itself. |
| 183 | +// |
| 184 | +// Isolation group names are only unique within one runtime of one discovery instance: |
| 185 | +// every process workload is in "host", and Kubernetes namespaces and Docker network names |
| 186 | +// repeat across clusters and hosts sharing a store. So a group only counts when both |
| 187 | +// workloads come from the same runtime and the same discovery instance. |
| 188 | +func (x *Workload) reachableFrom(fromID string, from *Workload) bool { |
| 189 | + if from == nil || from.GetId() != fromID || x.GetId() == fromID { |
| 190 | + return false |
| 191 | + } |
| 192 | + |
| 193 | + if !strings.EqualFold(x.GetRuntime(), from.GetRuntime()) || |
| 194 | + x.GetAnnotations()[DiscoveryInstanceAnnotation] != from.GetAnnotations()[DiscoveryInstanceAnnotation] { |
| 195 | + return false |
| 196 | + } |
| 197 | + |
| 198 | + for _, group := range x.GetIsolationGroups() { |
| 199 | + if slices.Contains(from.GetIsolationGroups(), group) { |
| 200 | + return true |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + return false |
| 205 | +} |
| 206 | + |
| 207 | +func containsFold(values []string, value string) bool { |
| 208 | + for _, v := range values { |
| 209 | + if strings.EqualFold(v, value) { |
| 210 | + return true |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + return false |
| 215 | +} |
| 216 | + |
| 217 | +func (x *Workload) hasLocatorProtocol(protocols []string) bool { |
| 218 | + for _, locator := range x.GetLocators() { |
| 219 | + if containsFold(protocols, locator.GetProtocol()) { |
| 220 | + return true |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + return false |
| 225 | +} |
| 226 | + |
| 227 | +// cardExtension returns the params of the card's extension whose URI is |
| 228 | +// <accepted schema URL>[/<version>]<objectPath>, or nil if there is none. |
| 229 | +func cardExtension(card map[string]*structpb.Value, objectPath string, acceptedSchemaURLs []string) map[string]*structpb.Value { |
| 230 | + extensions := card["capabilities"].GetStructValue().GetFields()["extensions"].GetListValue().GetValues() |
| 231 | + |
| 232 | + for _, extension := range extensions { |
| 233 | + fields := extension.GetStructValue().GetFields() |
| 234 | + if isAcceptedObjectURI(fields["uri"].GetStringValue(), objectPath, acceptedSchemaURLs) { |
| 235 | + return fields["params"].GetStructValue().GetFields() |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + return nil |
| 240 | +} |
| 241 | + |
| 242 | +// versionSegment matches the optional schema version between the schema URL and the object path. |
| 243 | +var versionSegment = regexp.MustCompile(`^(/[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?)?$`) |
| 244 | + |
| 245 | +func isAcceptedObjectURI(uri, objectPath string, acceptedSchemaURLs []string) bool { |
| 246 | + rest, ok := strings.CutSuffix(uri, objectPath) |
| 247 | + if !ok { |
| 248 | + return false |
| 249 | + } |
| 250 | + |
| 251 | + for _, base := range acceptedSchemaURLs { |
| 252 | + base = strings.TrimSuffix(base, "/") |
| 253 | + if version, ok := strings.CutPrefix(rest, base); ok && versionSegment.MatchString(version) { |
| 254 | + return true |
| 255 | + } |
| 256 | + } |
| 257 | + |
| 258 | + return false |
| 259 | +} |
| 260 | + |
| 261 | +func classes(value *structpb.Value) []OASFClass { |
| 262 | + items := value.GetListValue().GetValues() |
| 263 | + if len(items) == 0 { |
| 264 | + return nil |
| 265 | + } |
| 266 | + |
| 267 | + out := make([]OASFClass, 0, len(items)) |
| 268 | + |
| 269 | + for _, item := range items { |
| 270 | + fields := item.GetStructValue().GetFields() |
| 271 | + |
| 272 | + name := fields["name"].GetStringValue() |
| 273 | + if name == "" { |
| 274 | + continue |
| 275 | + } |
| 276 | + |
| 277 | + out = append(out, OASFClass{Name: name, ID: uint32(fields["id"].GetNumberValue())}) |
| 278 | + } |
| 279 | + |
| 280 | + return out |
| 281 | +} |
| 282 | + |
| 283 | +func classNames(classes []OASFClass) []string { |
| 284 | + names := make([]string, 0, len(classes)) |
| 285 | + for _, class := range classes { |
| 286 | + names = append(names, class.Name) |
| 287 | + } |
| 288 | + |
| 289 | + return names |
| 290 | +} |
| 291 | + |
| 292 | +// matchesAny reports whether any value matches any pattern. An empty pattern list matches. |
| 293 | +func matchesAny(patterns, values []string) bool { |
| 294 | + if len(patterns) == 0 { |
| 295 | + return true |
| 296 | + } |
| 297 | + |
| 298 | + for _, pattern := range patterns { |
| 299 | + for _, value := range values { |
| 300 | + if value != "" && matchPattern(pattern, value) { |
| 301 | + return true |
| 302 | + } |
| 303 | + } |
| 304 | + } |
| 305 | + |
| 306 | + return false |
| 307 | +} |
| 308 | + |
| 309 | +// matchPattern matches value against pattern as record search does: exactly (case-insensitive), |
| 310 | +// or with '*' matching any sequence of characters and '?' matching a single character. |
| 311 | +func matchPattern(pattern, value string) bool { |
| 312 | + if !strings.ContainsAny(pattern, "*?") { |
| 313 | + return strings.EqualFold(pattern, value) |
| 314 | + } |
| 315 | + |
| 316 | + var expr strings.Builder |
| 317 | + |
| 318 | + expr.WriteString("(?is)^") |
| 319 | + |
| 320 | + for _, r := range pattern { |
| 321 | + switch r { |
| 322 | + case '*': |
| 323 | + expr.WriteString(".*") |
| 324 | + case '?': |
| 325 | + expr.WriteString(".") |
| 326 | + default: |
| 327 | + expr.WriteString(regexp.QuoteMeta(string(r))) |
| 328 | + } |
| 329 | + } |
| 330 | + |
| 331 | + expr.WriteString("$") |
| 332 | + |
| 333 | + return regexp.MustCompile(expr.String()).MatchString(value) |
| 334 | +} |
0 commit comments