(ctx context.Context, policyRef string)
| 315 | } |
| 316 | |
| 317 | func (p *policy) loadPolicy(ctx context.Context, policyRef string) error { |
| 318 | if policyRef == "" { |
| 319 | log.Debug("Using an empty EnterpriseContractPolicy") |
| 320 | // Default to an empty policy instead of returning an error because the required |
| 321 | // values, e.g. PublicKey, may be provided via other means, e.g. |
| 322 | // publicKey param. |
| 323 | return nil |
| 324 | } |
| 325 | /* |
| 326 | Note: by the time we arrive here, if our policyRef was originally a URI for a |
| 327 | JSON / YAML the document will have already opened / downloaded and it would be |
| 328 | a JSON / YAML string which is why we can use `yaml.Unmarshal` below. |
| 329 | |
| 330 | Before we unmarshal we need to check if the policyRef text conforms to the |
| 331 | EnprerpriseContractPolicySpec schema. If it does, we can proceed to unmarshal |
| 332 | it. If it does not conform to the spec, we should return an error. |
| 333 | */ |
| 334 | if strings.Contains(policyRef, ":") { // Should detect JSON or YAML objects 🤞 |
| 335 | log.Debug("Read EnterpriseContractPolicy as YAML") |
| 336 | ecp := ecc.EnterpriseContractPolicy{} |
| 337 | if err := yaml.Unmarshal([]byte(policyRef), &ecp); err == nil && ecp.APIVersion != "" { |
| 338 | p.EnterpriseContractPolicySpec = ecp.Spec |
| 339 | } else { |
| 340 | log.Debugf("Unable to parse EnterpriseContractPolicy from %q", policyRef) |
| 341 | log.Debug("Attempting to parse as EnterpriseContractPolicySpec") |
| 342 | if err := yaml.Unmarshal([]byte(policyRef), &p.EnterpriseContractPolicySpec); err != nil { |
| 343 | log.Debugf("Unable to parse EnterpriseContractPolicySpec from %q", policyRef) |
| 344 | return fmt.Errorf("unable to parse EnterpriseContractPolicySpec: %w", err) |
| 345 | } |
| 346 | } |
| 347 | // Check if the policyRef is conformant to the schema |
| 348 | if policyRef != "" { |
| 349 | ok, err := p.isConformant(policyRef) |
| 350 | if err != nil { |
| 351 | return err |
| 352 | } |
| 353 | if !ok { |
| 354 | return fmt.Errorf("policy does not conform to the schema") |
| 355 | } |
| 356 | } |
| 357 | } else { |
| 358 | log.Debug("Read EnterpriseContractPolicy as k8s resource") |
| 359 | k8s, err := kubernetes.NewClient(ctx) |
| 360 | if err != nil { |
| 361 | log.Debug("Failed to initialize Kubernetes client") |
| 362 | return fmt.Errorf("cannot initialize Kubernetes client: %w", err) |
| 363 | } |
| 364 | log.Debug("Initialized Kubernetes client") |
| 365 | |
| 366 | ecp, err := k8s.FetchEnterpriseContractPolicy(ctx, policyRef) |
| 367 | if err != nil { |
| 368 | log.Debug("Failed to fetch the enterprise contract policy from the cluster!") |
| 369 | return fmt.Errorf("unable to fetch EnterpriseContractPolicy: %w", err) |
| 370 | } |
| 371 | p.EnterpriseContractPolicySpec = ecp.Spec |
| 372 | } |
| 373 | return nil |
| 374 | } |
no test coverage detected