Files
pmg/internal/audit/cloud_translate.go
T
327c9c7068 feat(cooldown): respect trusted_packages in dependency cooldown (#342)
* feat(cooldown): respect trusted_packages in dependency cooldown

Trusted packages are now treated as a superset waiver that bypasses every
PMG control (malware analysis, cooldown, and any future controls). A
globally trusted package is automatically exempt from the cooldown window
and no longer needs a duplicate entry in dependency_cooldown.skip.

The skip list remains the narrower, cooldown-only waiver for packages
that must bypass the cooldown wait but still be malware-scanned.

* refactor(cooldown): tag skip reason and audit-log skipped packages

Address review feedback on #342:

- Restore cooldownSkip to a pure single-list function (SRP); the merge
  into trusted_packages now happens in a separate mergeCooldownSkip step,
  driven by the exported CooldownSkip wrapper.
- Extend CooldownSkipInfo with a CooldownSkipReason (TrustedPackage /
  CooldownSkipList) on both SkipAll and per-version entries, so callers
  can tell apart the broad waiver from the cooldown-only one. When both
  lists match the same package, trusted_packages wins.
- Add audit.LogCooldownSkipped and emit it from the npm and PyPI
  interceptors on the SkipAll path, alongside the existing info log,
  carrying the source list as the reason.

* refactor(cooldown): inline list merge, audit per-version exemptions

Address further review feedback:

- Drop the separate mergeCooldownSkip helper; cooldownSkip now writes
  into a shared *CooldownSkipInfo and is called twice from CooldownSkip
  (cooldown skip list first, trusted_packages on top so trusted entries
  override the reason on overlap).
- Audit log every exemption, not just SkipAll: a new auditCooldownSkip
  helper in proxy/interceptors/cooldown.go emits one event per match
  (package-wide or per-version), each tagged with its source list.
  LogCooldownSkipped gains a version argument for the per-version case.
- Cover the trusted_packages reason path in TestCooldownSkip.

* fix(cooldown): avoid double-auditing trusted package exemptions

auditCooldownSkip now only emits EventTypeCooldownSkipped for entries
that came from dependency_cooldown.skip. Trusted-package exemptions
already get an EventTypeInstallTrustedAllowed event at tarball-download
time (proxy/interceptors/base_registry.go), so emitting a cooldown event
for them too would double-count the same waiver.

* emit trusted and cooldown skip events to cloud

* fix tests

* refactor(cooldown): return value from collectCooldownSkip, short-circuit on trusted SkipAll

Address PR review feedback:
- Rename cooldownSkip to collectCooldownSkip and return CooldownSkipInfo
  instead of mutating an input pointer.
- Add mergeCooldownSkip to combine per-list results with trusted_packages
  taking precedence on overlap.
- CooldownSkip now consults trusted_packages first and returns immediately
  on a package-wide trusted exemption (DC skip list cannot add anything).
- Extend tests to cover disjoint pinned entries across both lists and the
  case where DC version-less subsumes a trusted pinned entry.

* fix(audit): address cooldown review feedback

* fix(cooldown): audit cooldown skips at download time with concrete version

Backend rejects PackageVersion messages without a version, and audit logs
should reflect the runtime fact (a specific version was skipped) rather
than the config rule. Move the audit emission from metadata-request
handling to download-request handling, where the concrete version is
known, and require version in LogCooldownSkipped.

* chore(audit): drop dead scope assignment in LogCooldownSkipped

* refactor(cooldown): move skip-list logic into cooldown handlers

Registry interceptors no longer compute CooldownSkip or branch on SkipAll;
they just call HandleMetadataRequest. The npm and pypi cooldown handlers
own the skip lookup, the package-wide exemption short-circuit, and (for
pypi) the canonical-name denormalization. Also align LogCooldownSkipped
with other LogXxx signatures by taking *packagev1.PackageVersion.

* fix: Simplify audit logging for dependency cooldown skip

* refactor: Simplify cooldown handling and maintain separation of concepts for trusted and DC skip packages

* fix: Code review fixes

* fix: Emit cooldown skipped audit event ONLY when an in-window version is skipped

---------

Co-authored-by: Abhisek Datta <abhisek.datta@gmail.com>
2026-06-21 18:22:15 +05:30

210 lines
7.5 KiB
Go

package audit
import (
"fmt"
controltowerv1 "buf.build/gen/go/safedep/api/protocolbuffers/go/safedep/messages/controltower/v1"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
)
func (s *cloudSink) translateToPmgEvents(event AuditEvent) []*controltowerv1.PmgEvent {
switch event.Type {
case EventTypeMalwareBlocked:
return []*controltowerv1.PmgEvent{newPackageDecisionEvent(event, controltowerv1.PmgPackageAction_PMG_PACKAGE_ACTION_BLOCKED)}
case EventTypeMalwareConfirmed:
return []*controltowerv1.PmgEvent{newPackageDecisionEvent(event, controltowerv1.PmgPackageAction_PMG_PACKAGE_ACTION_CONFIRMED)}
case EventTypeCooldownSkipped:
return []*controltowerv1.PmgEvent{newPackageDecisionEvent(event, controltowerv1.PmgPackageAction_PMG_PACKAGE_ACTION_COOLDOWN_SKIPPED)}
case EventTypeInstallTrustedAllowed:
return []*controltowerv1.PmgEvent{newPackageDecisionEvent(event, controltowerv1.PmgPackageAction_PMG_PACKAGE_ACTION_TRUSTED)}
case EventTypeInstallInsecureBypass:
// PmgInsecureBypass is a session-level aggregate (package manager + total bypassed count),
// not a per-package event. It is emitted as part of EventTypeSessionComplete when
// the session's insecureBypassed counter is > 0.
return nil
case EventTypeDependencyCooldown:
return []*controltowerv1.PmgEvent{newCooldownBlockedEvent(event)}
case EventTypeProxyHostObserved:
return []*controltowerv1.PmgEvent{newHostObservationEvent(event)}
case EventTypeSandboxOverride:
return []*controltowerv1.PmgEvent{newSandboxOverrideEvent(event)}
case EventTypeError:
return []*controltowerv1.PmgEvent{newErrorEvent(event)}
case EventTypeSessionComplete:
if event.SessionData == nil {
return nil
}
events := []*controltowerv1.PmgEvent{newSessionSummaryEvent(event.SessionData)}
if event.SessionData.InsecureBypassed > 0 {
events = append(events, newInsecureBypassFromSession(event.SessionData))
}
return events
default:
return nil
}
}
func newPackageDecisionEvent(event AuditEvent, action controltowerv1.PmgPackageAction) *controltowerv1.PmgEvent {
decision := &controltowerv1.PmgPackageDecision{}
decision.SetPackageVersion(event.PackageVersion)
decision.SetAction(action)
if event.AnalysisID != "" {
decision.SetAnalysisId(event.AnalysisID)
}
decision.SetIsMalware(event.IsMalware)
decision.SetIsVerified(event.IsVerified)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_PACKAGE_DECISION)
e.SetPackageDecision(decision)
return e
}
func newSandboxOverrideEvent(event AuditEvent) *controltowerv1.PmgEvent {
override := &controltowerv1.PmgSandboxOverride{}
override.SetSandboxProfile(event.ProfileName)
var flattened []string
for _, m := range event.Overrides {
for k, v := range m {
flattened = append(flattened, fmt.Sprintf("%s:%s", k, v))
}
}
override.SetOverrides(flattened)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_SANDBOX_OVERRIDE)
e.SetSandboxOverride(override)
return e
}
func newErrorEvent(event AuditEvent) *controltowerv1.PmgEvent {
pmgErr := &controltowerv1.PmgError{}
if event.Error != nil {
pmgErr.SetErrorType(fmt.Sprintf("%T", event.Error))
}
pmgErr.SetMessage(event.Message)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_ERROR)
e.SetError(pmgErr)
return e
}
func newCooldownBlockedEvent(event AuditEvent) *controltowerv1.PmgEvent {
decision := &controltowerv1.PmgPackageDecision{}
decision.SetPackageVersion(event.PackageVersion)
decision.SetAction(controltowerv1.PmgPackageAction_PMG_PACKAGE_ACTION_COOLDOWN_BLOCKED)
cooldown := &controltowerv1.PmgDependencyCooldown{}
if !event.PublishDate.IsZero() {
cooldown.SetPublishDate(timestamppb.New(event.PublishDate))
}
cooldown.SetCooldownDays(uint32(event.CooldownDays))
cooldown.SetDaysSincePublish(uint32(event.DaysAgo))
cooldown.SetDaysRemaining(uint32(event.DaysLeft))
decision.SetCooldown(cooldown)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_PACKAGE_DECISION)
e.SetPackageDecision(decision)
return e
}
func newHostObservationEvent(event AuditEvent) *controltowerv1.PmgEvent {
obs := &controltowerv1.PmgHostObservation{}
obs.SetHostname(event.Hostname)
obs.SetMethod(event.Method)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_HOST_OBSERVATION)
e.SetHostObservation(obs)
return e
}
func newSessionSummaryEvent(data *SessionData) *controltowerv1.PmgEvent {
summary := &controltowerv1.PmgSessionSummary{}
summary.SetPackageManager(mapPackageManager(data.PackageManager))
summary.SetFlowType(mapFlowType(data.FlowType))
summary.SetTotalAnalyzed(data.TotalAnalyzed)
summary.SetAllowedCount(data.AllowedCount)
summary.SetBlockedCount(data.BlockedCount)
summary.SetConfirmedCount(data.ConfirmedCount)
summary.SetTrustedSkipped(data.TrustedSkipped)
summary.SetCooldownBlockedCount(data.CooldownBlockedCount)
summary.SetDuration(durationpb.New(data.Duration))
summary.SetSandboxEnabled(data.SandboxEnabled)
summary.SetParanoidMode(data.ParanoidMode)
summary.SetTransitiveEnabled(data.TransitiveEnabled)
summary.SetOutcome(mapSessionOutcome(data.Outcome))
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_SESSION_SUMMARY)
e.SetSessionSummary(summary)
return e
}
func newInsecureBypassFromSession(data *SessionData) *controltowerv1.PmgEvent {
bypass := &controltowerv1.PmgInsecureBypass{}
bypass.SetPackageManager(mapPackageManager(data.PackageManager))
bypass.SetPackagesBypassed(data.InsecureBypassed)
e := &controltowerv1.PmgEvent{}
e.SetEventType(controltowerv1.PmgEventType_PMG_EVENT_TYPE_INSECURE_BYPASS)
e.SetInsecureBypass(bypass)
return e
}
func mapFlowType(ft FlowType) controltowerv1.PmgFlowType {
switch ft {
case FlowTypeGuard:
return controltowerv1.PmgFlowType_PMG_FLOW_TYPE_GUARD
case FlowTypeProxy:
return controltowerv1.PmgFlowType_PMG_FLOW_TYPE_PROXY
default:
return controltowerv1.PmgFlowType_PMG_FLOW_TYPE_UNSPECIFIED
}
}
func mapSessionOutcome(outcome Outcome) controltowerv1.PmgSessionOutcome {
switch outcome {
case OutcomeSuccess:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_SUCCESS
case OutcomeBlocked:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_BLOCKED
case OutcomeUserCancelled:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_USER_CANCELLED
case OutcomeError:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_ERROR
case OutcomeDryRun:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_DRY_RUN
case OutcomeInsecureBypass:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_INSECURE_BYPASS
default:
return controltowerv1.PmgSessionOutcome_PMG_SESSION_OUTCOME_UNSPECIFIED
}
}
func mapPackageManager(name string) controltowerv1.PmgPackageManager {
switch name {
case "npm", "npx":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_NPM
case "pnpm", "pnpx":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_PNPM
case "yarn":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_YARN
case "bun":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_BUN
case "pip", "pip3", "pipx":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_PIP
case "poetry":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_POETRY
case "uv":
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_UV
default:
return controltowerv1.PmgPackageManager_PMG_PACKAGE_MANAGER_UNSPECIFIED
}
}