diff --git a/README.md b/README.md index b870622..15fef5f 100644 --- a/README.md +++ b/README.md @@ -44,16 +44,40 @@ see live on separate staff-only kinds (`SubmissionReview`, Vote and Subscription names are `.`, which gives one per user per post across the shared collection. +The `owner` admission webhook sets `spec.userRef` on every user-owned kind +from the request: in a user's own context it is always that user. Only the +operator creates them for someone else, and the Security Team logs reports +for external reporters with no owner. The `reviewer` webhook records who +decided on a `SubmissionReview`. + +## Roles + +| Role | For | +| --- | --- | +| `feedback.miloapis.com-user` | every signed-in user, in their own context, through Milo's `iam-user-self-manage` | +| `feedback.miloapis.com-public-reader` | the datum.net service account | +| `feedback.miloapis.com-viewer`, `-editor`, `-reviewer`, `-admin` | staff | +| `feedback.miloapis.com-security-team` | the Security Team only; the only role that reads every report and their triage | + +The service's components (`system:feedback-operator`, `system:feedback-sync`, +`system:feedback-uploads`, all `@feedback.miloapis.com`) authenticate with +client certificates and get Kubernetes RBAC in Milo (`config/milo/rbac`). + ## Layout ``` cmd/feedback/ operator and version commands +internal/identity/ who a request comes from, from Milo's user info +internal/webhook/ admission webhooks Milo calls pkg/apis/feedback/ feedback.miloapis.com/v1alpha1 types (CRDs) config/crd/ generated CRDs, installed in Milo config/base/ operator Deployment, Services, leader election RBAC config/components/ milo-integration: Milo kubeconfig, client and webhook certificates -config/milo/ Milo IAM ProtectedResources and Roles +config/milo/ applied to Milo: IAM (iam/), RBAC for the service's + components (rbac/), webhook config (webhook/), and + optional role bindings (bindings/) config/samples/ an example of every resource +test/config/ checks config/ against the CRDs ``` ## Development diff --git a/Taskfile.yaml b/Taskfile.yaml index 60413d4..5d2cf08 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -42,6 +42,7 @@ tasks: cmds: - "{{.TOOL_DIR}}/controller-gen object:headerFile=hack/boilerplate.go.txt paths=./pkg/apis/..." - "{{.TOOL_DIR}}/controller-gen crd paths=./pkg/apis/... output:crd:artifacts:config=config/crd/bases" + - "{{.TOOL_DIR}}/controller-gen webhook paths=./internal/webhook/... output:webhook:artifacts:config=config/milo/webhook" install-tools: desc: Install code generators into bin/ diff --git a/cmd/feedback/operator.go b/cmd/feedback/operator.go index a6dc16e..00263cb 100644 --- a/cmd/feedback/operator.go +++ b/cmd/feedback/operator.go @@ -14,9 +14,10 @@ import ( "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" - "sigs.k8s.io/controller-runtime/pkg/webhook" + ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook" "go.miloapis.com/feedback/internal/version" + "go.miloapis.com/feedback/internal/webhook" feedbackv1alpha1 "go.miloapis.com/feedback/pkg/apis/feedback/v1alpha1" ) @@ -86,12 +87,14 @@ func runOperator(o operatorOptions) error { LeaderElectionNamespace: o.leaderElectionNamespace, LeaderElectionConfig: localConfig, LeaderElectionReleaseOnCancel: true, - WebhookServer: webhook.NewServer(webhook.Options{Port: o.webhookPort, CertDir: o.webhookCertDir}), + WebhookServer: ctrlwebhook.NewServer(ctrlwebhook.Options{Port: o.webhookPort, CertDir: o.webhookCertDir}), }) if err != nil { return fmt.Errorf("creating manager: %w", err) } + webhook.Register(mgr) + if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { return err } diff --git a/config/milo/bindings/kustomization.yaml b/config/milo/bindings/kustomization.yaml new file mode 100644 index 0000000..eb09c8f --- /dev/null +++ b/config/milo/bindings/kustomization.yaml @@ -0,0 +1,29 @@ +# Who gets which role, platform-wide. Optional: a deployment includes this +# component, or binds the roles to its own groups instead. +# +# - feedback-security-team gets the security-team role on reports. +# - staff-users get the reviewer role on everything else. PolicyBindings +# select one kind each, so there is one file per kind. +# +# Users get feedback.miloapis.com-user on their own User by adding it to +# inheritedRoles of Milo's iam-user-self-manage role. That role is shared +# with other services, so the deployment patches it, keeping their entries. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +resources: + - security-team-group.yaml + - security-team-securityreports.yaml + - security-team-securityreporttriages.yaml + - security-team-securityacknowledgements.yaml + - staff-reviewer-feedbacksources.yaml + - staff-reviewer-posts.yaml + - staff-reviewer-releases.yaml + - staff-reviewer-changelogentries.yaml + - staff-reviewer-votes.yaml + - staff-reviewer-subscriptions.yaml + - staff-reviewer-submissions.yaml + - staff-reviewer-submissionreviews.yaml + - staff-reviewer-securityacknowledgements.yaml + - staff-reviewer-feedbackprofiles.yaml + - staff-reviewer-feedbackdigests.yaml diff --git a/config/milo/bindings/security-team-group.yaml b/config/milo/bindings/security-team-group.yaml new file mode 100644 index 0000000..0a015a5 --- /dev/null +++ b/config/milo/bindings/security-team-group.yaml @@ -0,0 +1,7 @@ +# Members are added with GroupMemberships. Keep it to the people who handle +# vulnerability reports: membership grants every report's contents. +apiVersion: iam.miloapis.com/v1alpha1 +kind: Group +metadata: + name: feedback-security-team + namespace: milo-system diff --git a/config/milo/bindings/security-team-securityacknowledgements.yaml b/config/milo/bindings/security-team-securityacknowledgements.yaml new file mode 100644 index 0000000..0327441 --- /dev/null +++ b/config/milo/bindings/security-team-securityacknowledgements.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-security-team-securityacknowledgements + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-security-team + namespace: milo-system + subjects: + - kind: Group + name: feedback-security-team + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: SecurityAcknowledgement diff --git a/config/milo/bindings/security-team-securityreports.yaml b/config/milo/bindings/security-team-securityreports.yaml new file mode 100644 index 0000000..ae8cd6d --- /dev/null +++ b/config/milo/bindings/security-team-securityreports.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-security-team-securityreports + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-security-team + namespace: milo-system + subjects: + - kind: Group + name: feedback-security-team + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: SecurityReport diff --git a/config/milo/bindings/security-team-securityreporttriages.yaml b/config/milo/bindings/security-team-securityreporttriages.yaml new file mode 100644 index 0000000..c052234 --- /dev/null +++ b/config/milo/bindings/security-team-securityreporttriages.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-security-team-securityreporttriages + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-security-team + namespace: milo-system + subjects: + - kind: Group + name: feedback-security-team + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: SecurityReportTriage diff --git a/config/milo/bindings/staff-reviewer-changelogentries.yaml b/config/milo/bindings/staff-reviewer-changelogentries.yaml new file mode 100644 index 0000000..2e535d9 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-changelogentries.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-changelogentries + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: ChangelogEntry diff --git a/config/milo/bindings/staff-reviewer-feedbackdigests.yaml b/config/milo/bindings/staff-reviewer-feedbackdigests.yaml new file mode 100644 index 0000000..8a34cc2 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-feedbackdigests.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-feedbackdigests + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: FeedbackDigest diff --git a/config/milo/bindings/staff-reviewer-feedbackprofiles.yaml b/config/milo/bindings/staff-reviewer-feedbackprofiles.yaml new file mode 100644 index 0000000..bd50156 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-feedbackprofiles.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-feedbackprofiles + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: FeedbackProfile diff --git a/config/milo/bindings/staff-reviewer-feedbacksources.yaml b/config/milo/bindings/staff-reviewer-feedbacksources.yaml new file mode 100644 index 0000000..20d5950 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-feedbacksources.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-feedbacksources + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: FeedbackSource diff --git a/config/milo/bindings/staff-reviewer-posts.yaml b/config/milo/bindings/staff-reviewer-posts.yaml new file mode 100644 index 0000000..089972d --- /dev/null +++ b/config/milo/bindings/staff-reviewer-posts.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-posts + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: Post diff --git a/config/milo/bindings/staff-reviewer-releases.yaml b/config/milo/bindings/staff-reviewer-releases.yaml new file mode 100644 index 0000000..6841688 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-releases.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-releases + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: Release diff --git a/config/milo/bindings/staff-reviewer-securityacknowledgements.yaml b/config/milo/bindings/staff-reviewer-securityacknowledgements.yaml new file mode 100644 index 0000000..d1c9c10 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-securityacknowledgements.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-securityacknowledgements + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: SecurityAcknowledgement diff --git a/config/milo/bindings/staff-reviewer-submissionreviews.yaml b/config/milo/bindings/staff-reviewer-submissionreviews.yaml new file mode 100644 index 0000000..01bb24a --- /dev/null +++ b/config/milo/bindings/staff-reviewer-submissionreviews.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-submissionreviews + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: SubmissionReview diff --git a/config/milo/bindings/staff-reviewer-submissions.yaml b/config/milo/bindings/staff-reviewer-submissions.yaml new file mode 100644 index 0000000..8e42abb --- /dev/null +++ b/config/milo/bindings/staff-reviewer-submissions.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-submissions + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: Submission diff --git a/config/milo/bindings/staff-reviewer-subscriptions.yaml b/config/milo/bindings/staff-reviewer-subscriptions.yaml new file mode 100644 index 0000000..66389df --- /dev/null +++ b/config/milo/bindings/staff-reviewer-subscriptions.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-subscriptions + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: Subscription diff --git a/config/milo/bindings/staff-reviewer-votes.yaml b/config/milo/bindings/staff-reviewer-votes.yaml new file mode 100644 index 0000000..514e5f2 --- /dev/null +++ b/config/milo/bindings/staff-reviewer-votes.yaml @@ -0,0 +1,17 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: PolicyBinding +metadata: + name: feedback-staff-reviewer-votes + namespace: milo-system +spec: + roleRef: + name: feedback.miloapis.com-reviewer + namespace: milo-system + subjects: + - kind: Group + name: staff-users + namespace: milo-system + resourceSelector: + resourceKind: + apiGroup: feedback.miloapis.com + kind: Vote diff --git a/config/milo/iam/resources/changelogentries.yaml b/config/milo/iam/resources/changelogentries.yaml new file mode 100644 index 0000000..a79511a --- /dev/null +++ b/config/milo/iam/resources/changelogentries.yaml @@ -0,0 +1,27 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-changelogentries +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: ChangelogEntry + plural: changelogentries + singular: changelogentry + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/feedbackdigests.yaml b/config/milo/iam/resources/feedbackdigests.yaml new file mode 100644 index 0000000..e3fb6c3 --- /dev/null +++ b/config/milo/iam/resources/feedbackdigests.yaml @@ -0,0 +1,18 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-feedbackdigests +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: FeedbackDigest + plural: feedbackdigests + singular: feedbackdigest + permissions: + - get + - list + - watch + - create + - update + - patch + - delete diff --git a/config/milo/iam/resources/feedbackprofiles.yaml b/config/milo/iam/resources/feedbackprofiles.yaml new file mode 100644 index 0000000..c96cfba --- /dev/null +++ b/config/milo/iam/resources/feedbackprofiles.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-feedbackprofiles +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: FeedbackProfile + plural: feedbackprofiles + singular: feedbackprofile + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/feedbacksources.yaml b/config/milo/iam/resources/feedbacksources.yaml index 86c3903..e925a1b 100644 --- a/config/milo/iam/resources/feedbacksources.yaml +++ b/config/milo/iam/resources/feedbacksources.yaml @@ -15,10 +15,10 @@ spec: - update - patch permissions: - - list - get + - list + - watch - create - update - - delete - patch - - watch + - delete diff --git a/config/milo/iam/resources/kustomization.yaml b/config/milo/iam/resources/kustomization.yaml index b450c78..f1f8e1a 100644 --- a/config/milo/iam/resources/kustomization.yaml +++ b/config/milo/iam/resources/kustomization.yaml @@ -3,3 +3,15 @@ kind: Component resources: - feedbacksources.yaml + - posts.yaml + - releases.yaml + - changelogentries.yaml + - votes.yaml + - subscriptions.yaml + - submissions.yaml + - submissionreviews.yaml + - securityreports.yaml + - securityreporttriages.yaml + - securityacknowledgements.yaml + - feedbackprofiles.yaml + - feedbackdigests.yaml diff --git a/config/milo/iam/resources/posts.yaml b/config/milo/iam/resources/posts.yaml new file mode 100644 index 0000000..085affd --- /dev/null +++ b/config/milo/iam/resources/posts.yaml @@ -0,0 +1,33 @@ +# posts/hidden isn't served. Milo asks whether the caller may get it before +# showing hidden posts (iam.miloapis.com/hidden-field on the CRD). Grant it to +# staff and the service's own components only. +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-posts +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: Post + plural: posts + singular: post + subresources: + - name: status + permissions: + - get + - update + - patch + - name: hidden + permissions: + - get + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/releases.yaml b/config/milo/iam/resources/releases.yaml new file mode 100644 index 0000000..80276f0 --- /dev/null +++ b/config/milo/iam/resources/releases.yaml @@ -0,0 +1,27 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-releases +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: Release + plural: releases + singular: release + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/securityacknowledgements.yaml b/config/milo/iam/resources/securityacknowledgements.yaml new file mode 100644 index 0000000..e299400 --- /dev/null +++ b/config/milo/iam/resources/securityacknowledgements.yaml @@ -0,0 +1,18 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-securityacknowledgements +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: SecurityAcknowledgement + plural: securityacknowledgements + singular: securityacknowledgement + permissions: + - get + - list + - watch + - create + - update + - patch + - delete diff --git a/config/milo/iam/resources/securityreports.yaml b/config/milo/iam/resources/securityreports.yaml new file mode 100644 index 0000000..7b435f0 --- /dev/null +++ b/config/milo/iam/resources/securityreports.yaml @@ -0,0 +1,27 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-securityreports +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: SecurityReport + plural: securityreports + singular: securityreport + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/securityreporttriages.yaml b/config/milo/iam/resources/securityreporttriages.yaml new file mode 100644 index 0000000..ffa300b --- /dev/null +++ b/config/milo/iam/resources/securityreporttriages.yaml @@ -0,0 +1,18 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-securityreporttriages +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: SecurityReportTriage + plural: securityreporttriages + singular: securityreporttriage + permissions: + - get + - list + - watch + - create + - update + - patch + - delete diff --git a/config/milo/iam/resources/submissionreviews.yaml b/config/milo/iam/resources/submissionreviews.yaml new file mode 100644 index 0000000..0c5d954 --- /dev/null +++ b/config/milo/iam/resources/submissionreviews.yaml @@ -0,0 +1,24 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-submissionreviews +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: SubmissionReview + plural: submissionreviews + singular: submissionreview + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete diff --git a/config/milo/iam/resources/submissions.yaml b/config/milo/iam/resources/submissions.yaml new file mode 100644 index 0000000..b3efe17 --- /dev/null +++ b/config/milo/iam/resources/submissions.yaml @@ -0,0 +1,27 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-submissions +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: Submission + plural: submissions + singular: submission + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/subscriptions.yaml b/config/milo/iam/resources/subscriptions.yaml new file mode 100644 index 0000000..1b14537 --- /dev/null +++ b/config/milo/iam/resources/subscriptions.yaml @@ -0,0 +1,21 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-subscriptions +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: Subscription + plural: subscriptions + singular: subscription + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/resources/votes.yaml b/config/milo/iam/resources/votes.yaml new file mode 100644 index 0000000..2ef8cee --- /dev/null +++ b/config/milo/iam/resources/votes.yaml @@ -0,0 +1,27 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: feedback.miloapis.com-votes +spec: + serviceRef: + name: "feedback.miloapis.com" + kind: Vote + plural: votes + singular: vote + subresources: + - name: status + permissions: + - get + - update + - patch + permissions: + - get + - list + - watch + - create + - update + - patch + - delete + parentResources: + - apiGroup: iam.miloapis.com + kind: User diff --git a/config/milo/iam/roles/admin.yaml b/config/milo/iam/roles/admin.yaml index d680418..9a72671 100644 --- a/config/milo/iam/roles/admin.yaml +++ b/config/milo/iam/roles/admin.yaml @@ -6,10 +6,15 @@ metadata: labels: app.kubernetes.io/name: admin app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Admin + kubernetes.io/description: "Everything an editor and a reviewer can do, plus deleting feedback sources. Security reports stay with the Security Team role." spec: launchStage: Alpha inheritedRoles: - name: feedback.miloapis.com-editor namespace: milo-system + - name: feedback.miloapis.com-reviewer + namespace: milo-system includedPermissions: - feedback.miloapis.com/feedbacksources.delete diff --git a/config/milo/iam/roles/editor.yaml b/config/milo/iam/roles/editor.yaml index 18362c1..faee26b 100644 --- a/config/milo/iam/roles/editor.yaml +++ b/config/milo/iam/roles/editor.yaml @@ -6,6 +6,9 @@ metadata: labels: app.kubernetes.io/name: editor app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Editor + kubernetes.io/description: "Configures which GitHub repositories feed the roadmap, on top of viewer access." spec: launchStage: Alpha inheritedRoles: diff --git a/config/milo/iam/roles/kustomization.yaml b/config/milo/iam/roles/kustomization.yaml index e539027..9dbc361 100644 --- a/config/milo/iam/roles/kustomization.yaml +++ b/config/milo/iam/roles/kustomization.yaml @@ -2,6 +2,10 @@ apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component resources: + - user.yaml + - public-reader.yaml - viewer.yaml + - reviewer.yaml - editor.yaml - admin.yaml + - security-team.yaml diff --git a/config/milo/iam/roles/public-reader.yaml b/config/milo/iam/roles/public-reader.yaml new file mode 100644 index 0000000..7627676 --- /dev/null +++ b/config/milo/iam/roles/public-reader.yaml @@ -0,0 +1,22 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: feedback.miloapis.com-public-reader + namespace: milo-system + labels: + app.kubernetes.io/name: public-reader + app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Public Reader + kubernetes.io/description: "Reads what datum.net shows: visible posts, releases, changelog entries and security acknowledgements." +spec: + launchStage: Alpha + includedPermissions: + - feedback.miloapis.com/posts.get + - feedback.miloapis.com/posts.list + - feedback.miloapis.com/releases.get + - feedback.miloapis.com/releases.list + - feedback.miloapis.com/changelogentries.get + - feedback.miloapis.com/changelogentries.list + - feedback.miloapis.com/securityacknowledgements.get + - feedback.miloapis.com/securityacknowledgements.list diff --git a/config/milo/iam/roles/reviewer.yaml b/config/milo/iam/roles/reviewer.yaml new file mode 100644 index 0000000..18fed32 --- /dev/null +++ b/config/milo/iam/roles/reviewer.yaml @@ -0,0 +1,30 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: feedback.miloapis.com-reviewer + namespace: milo-system + labels: + app.kubernetes.io/name: reviewer + app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Reviewer + kubernetes.io/description: "Works the feedback queue: reads submissions, decides on them through their reviews (including moving misfiled ones to the security track), deletes spam, and hides posts. Cannot see security reports." +spec: + launchStage: Alpha + inheritedRoles: + - name: feedback.miloapis.com-viewer + namespace: milo-system + includedPermissions: + - feedback.miloapis.com/posts.update + - feedback.miloapis.com/posts.patch + - feedback.miloapis.com/submissions.get + - feedback.miloapis.com/submissions.list + - feedback.miloapis.com/submissions.watch + - feedback.miloapis.com/submissions.delete + - feedback.miloapis.com/submissions/status.get + - feedback.miloapis.com/submissionreviews.get + - feedback.miloapis.com/submissionreviews.list + - feedback.miloapis.com/submissionreviews.watch + - feedback.miloapis.com/submissionreviews.update + - feedback.miloapis.com/submissionreviews.patch + - feedback.miloapis.com/submissionreviews/status.get diff --git a/config/milo/iam/roles/security-team.yaml b/config/milo/iam/roles/security-team.yaml new file mode 100644 index 0000000..46197c0 --- /dev/null +++ b/config/milo/iam/roles/security-team.yaml @@ -0,0 +1,34 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: feedback.miloapis.com-security-team + namespace: milo-system + labels: + app.kubernetes.io/name: security-team + app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Security Team + kubernetes.io/description: "Works vulnerability reports: reads every report and its private triage, logs reports from email and GitHub, and writes status. Separate from feedback reviewers." +spec: + launchStage: Alpha + includedPermissions: + - feedback.miloapis.com/securityreports.get + - feedback.miloapis.com/securityreports.list + - feedback.miloapis.com/securityreports.watch + - feedback.miloapis.com/securityreports.create + - feedback.miloapis.com/securityreports.update + - feedback.miloapis.com/securityreports.patch + - feedback.miloapis.com/securityreports.delete + - feedback.miloapis.com/securityreports/status.get + - feedback.miloapis.com/securityreports/status.update + - feedback.miloapis.com/securityreports/status.patch + - feedback.miloapis.com/securityreporttriages.get + - feedback.miloapis.com/securityreporttriages.list + - feedback.miloapis.com/securityreporttriages.watch + - feedback.miloapis.com/securityreporttriages.create + - feedback.miloapis.com/securityreporttriages.update + - feedback.miloapis.com/securityreporttriages.patch + - feedback.miloapis.com/securityreporttriages.delete + - feedback.miloapis.com/securityacknowledgements.get + - feedback.miloapis.com/securityacknowledgements.list + - feedback.miloapis.com/securityacknowledgements.watch diff --git a/config/milo/iam/roles/user.yaml b/config/milo/iam/roles/user.yaml new file mode 100644 index 0000000..b43c651 --- /dev/null +++ b/config/milo/iam/roles/user.yaml @@ -0,0 +1,39 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: feedback.miloapis.com-user + namespace: milo-system + labels: + app.kubernetes.io/name: user + app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback User + kubernetes.io/description: "What every signed-in user can do with feedback in their own user context: browse posts, vote, follow, send feedback and security reports, set their feedback profile, and read their own. Milo limits each user to their own objects." +spec: + launchStage: Alpha + includedPermissions: + - feedback.miloapis.com/posts.get + - feedback.miloapis.com/posts.list + - feedback.miloapis.com/releases.get + - feedback.miloapis.com/releases.list + - feedback.miloapis.com/changelogentries.get + - feedback.miloapis.com/changelogentries.list + - feedback.miloapis.com/votes.get + - feedback.miloapis.com/votes.list + - feedback.miloapis.com/votes.create + - feedback.miloapis.com/votes.delete + - feedback.miloapis.com/subscriptions.get + - feedback.miloapis.com/subscriptions.list + - feedback.miloapis.com/subscriptions.create + - feedback.miloapis.com/subscriptions.delete + - feedback.miloapis.com/submissions.get + - feedback.miloapis.com/submissions.list + - feedback.miloapis.com/submissions.create + - feedback.miloapis.com/securityreports.get + - feedback.miloapis.com/securityreports.list + - feedback.miloapis.com/securityreports.create + - feedback.miloapis.com/feedbackprofiles.get + - feedback.miloapis.com/feedbackprofiles.list + - feedback.miloapis.com/feedbackprofiles.create + - feedback.miloapis.com/feedbackprofiles.update + - feedback.miloapis.com/feedbackprofiles.patch diff --git a/config/milo/iam/roles/viewer.yaml b/config/milo/iam/roles/viewer.yaml index a0e43a9..0de02bc 100644 --- a/config/milo/iam/roles/viewer.yaml +++ b/config/milo/iam/roles/viewer.yaml @@ -6,6 +6,9 @@ metadata: labels: app.kubernetes.io/name: viewer app.kubernetes.io/part-of: feedback.miloapis.com + annotations: + kubernetes.io/display-name: Feedback Viewer + kubernetes.io/description: "Staff read access to feedback: sources, every post including hidden ones, releases, changelog entries, votes, follows, profiles and digests across users. No submissions or security reports." spec: launchStage: Alpha includedPermissions: @@ -13,3 +16,29 @@ spec: - feedback.miloapis.com/feedbacksources.list - feedback.miloapis.com/feedbacksources.watch - feedback.miloapis.com/feedbacksources/status.get + - feedback.miloapis.com/posts.get + - feedback.miloapis.com/posts.list + - feedback.miloapis.com/posts.watch + - feedback.miloapis.com/posts/status.get + - feedback.miloapis.com/posts/hidden.get + - feedback.miloapis.com/releases.get + - feedback.miloapis.com/releases.list + - feedback.miloapis.com/releases.watch + - feedback.miloapis.com/changelogentries.get + - feedback.miloapis.com/changelogentries.list + - feedback.miloapis.com/changelogentries.watch + - feedback.miloapis.com/votes.get + - feedback.miloapis.com/votes.list + - feedback.miloapis.com/votes.watch + - feedback.miloapis.com/subscriptions.get + - feedback.miloapis.com/subscriptions.list + - feedback.miloapis.com/subscriptions.watch + - feedback.miloapis.com/feedbackprofiles.get + - feedback.miloapis.com/feedbackprofiles.list + - feedback.miloapis.com/feedbackprofiles.watch + - feedback.miloapis.com/feedbackdigests.get + - feedback.miloapis.com/feedbackdigests.list + - feedback.miloapis.com/feedbackdigests.watch + - feedback.miloapis.com/securityacknowledgements.get + - feedback.miloapis.com/securityacknowledgements.list + - feedback.miloapis.com/securityacknowledgements.watch diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index 66e668c..95beac3 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -1,7 +1,11 @@ +# What the service registers in Milo: ProtectedResources and Roles (iam/), +# Kubernetes RBAC for the service's own components (rbac/) and the admission +# webhooks Milo calls (webhook/). The CRDs are in config/crd. bindings/ is +# separate and optional: who holds the roles is the deployment's choice. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component -# Applied to Milo. The CRDs themselves are in config/crd; each CRD declares -# its discovery contexts and access rules with annotations. components: - iam/ + - rbac/ + - webhook/ diff --git a/config/milo/rbac/feedback-operator.yaml b/config/milo/rbac/feedback-operator.yaml new file mode 100644 index 0000000..ee33110 --- /dev/null +++ b/config/milo/rbac/feedback-operator.yaml @@ -0,0 +1,37 @@ +# feedback-operator reconciles every feedback resource: it watches them all, +# writes post votes and delivery, follows and votes it creates for users, +# review outcomes, reports moved from submissions, acknowledgements and +# digests. It never writes a post's GitHub fields or a user's spec. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: feedback.miloapis.com:operator +rules: + - apiGroups: [feedback.miloapis.com] + resources: [feedbacksources, posts, releases, changelogentries, votes, subscriptions, submissions, submissionreviews, securityreports, securityreporttriages, securityacknowledgements, feedbackprofiles, feedbackdigests] + verbs: [get, list, watch] + - apiGroups: [feedback.miloapis.com] + resources: [posts/hidden] + verbs: [get] + - apiGroups: [feedback.miloapis.com] + resources: [posts/status, votes/status, submissions/status, submissionreviews/status, securityreports/status] + verbs: [get, update, patch] + - apiGroups: [feedback.miloapis.com] + resources: [votes, subscriptions, submissionreviews, securityreports, securityacknowledgements, feedbackdigests] + verbs: [create, update, patch, delete] + - apiGroups: [feedback.miloapis.com] + resources: [submissions] + verbs: [delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: feedback.miloapis.com:operator +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: feedback.miloapis.com:operator +subjects: + - apiGroup: rbac.authorization.k8s.io + kind: User + name: system:feedback-operator@feedback.miloapis.com diff --git a/config/milo/rbac/feedback-sync.yaml b/config/milo/rbac/feedback-sync.yaml new file mode 100644 index 0000000..a4a302b --- /dev/null +++ b/config/milo/rbac/feedback-sync.yaml @@ -0,0 +1,40 @@ +# feedback-sync mirrors GitHub into posts, releases and changelog entries, +# and reads its FeedbackSources and approved submission reviews. It +# authenticates to Milo with a client certificate whose common name is the +# subject below. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: feedback.miloapis.com:sync +rules: + - apiGroups: [feedback.miloapis.com] + resources: [feedbacksources] + verbs: [get, list, watch] + - apiGroups: [feedback.miloapis.com] + resources: [feedbacksources/status] + verbs: [get, update, patch] + - apiGroups: [feedback.miloapis.com] + resources: [posts, releases, changelogentries] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [feedback.miloapis.com] + resources: [posts/status, releases/status, changelogentries/status] + verbs: [get, update, patch] + - apiGroups: [feedback.miloapis.com] + resources: [posts/hidden] + verbs: [get] + - apiGroups: [feedback.miloapis.com] + resources: [submissionreviews] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: feedback.miloapis.com:sync +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: feedback.miloapis.com:sync +subjects: + - apiGroup: rbac.authorization.k8s.io + kind: User + name: system:feedback-sync@feedback.miloapis.com diff --git a/config/milo/rbac/feedback-uploads.yaml b/config/milo/rbac/feedback-uploads.yaml new file mode 100644 index 0000000..d3a92b8 --- /dev/null +++ b/config/milo/rbac/feedback-uploads.yaml @@ -0,0 +1,50 @@ +# feedback-uploads stores attachments. It checks the caller with TokenReview +# and SubjectAccessReview (granted separately below) and reads submissions and +# reports to find which files they reference. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: feedback.miloapis.com:uploads +rules: + - apiGroups: [feedback.miloapis.com] + resources: [submissions, securityreports] + verbs: [get] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: feedback.miloapis.com:uploads +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: feedback.miloapis.com:uploads +subjects: + - apiGroup: rbac.authorization.k8s.io + kind: User + name: system:feedback-uploads@feedback.miloapis.com +--- +# Authenticating and authorizing callers on Milo's behalf. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: feedback.miloapis.com:uploads-reviews +rules: + - apiGroups: [authentication.k8s.io] + resources: [tokenreviews] + verbs: [create] + - apiGroups: [authorization.k8s.io] + resources: [subjectaccessreviews] + verbs: [create] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: feedback.miloapis.com:uploads-reviews +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: feedback.miloapis.com:uploads-reviews +subjects: + - apiGroup: rbac.authorization.k8s.io + kind: User + name: system:feedback-uploads@feedback.miloapis.com diff --git a/config/milo/rbac/kustomization.yaml b/config/milo/rbac/kustomization.yaml new file mode 100644 index 0000000..adddfc1 --- /dev/null +++ b/config/milo/rbac/kustomization.yaml @@ -0,0 +1,9 @@ +# Kubernetes RBAC in Milo for the service's own components, which +# authenticate with client certificates rather than as Milo users. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +resources: + - feedback-operator.yaml + - feedback-sync.yaml + - feedback-uploads.yaml diff --git a/config/milo/webhook/kustomization.yaml b/config/milo/webhook/kustomization.yaml new file mode 100644 index 0000000..2754532 --- /dev/null +++ b/config/milo/webhook/kustomization.yaml @@ -0,0 +1,33 @@ +# The admission webhooks Milo calls for feedback resources. manifests.yaml is +# generated by `task generate`; the patches point it at the operator's +# Service. Milo trusts certificates from the datum-control-plane issuer, so +# there is no caBundle. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +resources: + - manifests.yaml + +patches: + - target: + kind: MutatingWebhookConfiguration + name: mutating-webhook-configuration + patch: |- + - op: replace + path: /metadata/name + value: feedback.miloapis.com + - target: + kind: MutatingWebhookConfiguration + patch: |- + - op: replace + path: /webhooks/0/clientConfig/service/name + value: feedback-operator-webhook + - op: replace + path: /webhooks/0/clientConfig/service/namespace + value: feedback-system + - op: replace + path: /webhooks/1/clientConfig/service/name + value: feedback-operator-webhook + - op: replace + path: /webhooks/1/clientConfig/service/namespace + value: feedback-system diff --git a/config/milo/webhook/manifests.yaml b/config/milo/webhook/manifests.yaml new file mode 100644 index 0000000..4156f0e --- /dev/null +++ b/config/milo/webhook/manifests.yaml @@ -0,0 +1,49 @@ +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: mutating-webhook-configuration +webhooks: +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /mutate-owner + failurePolicy: Fail + name: owner.feedback.miloapis.com + rules: + - apiGroups: + - feedback.miloapis.com + apiVersions: + - v1alpha1 + operations: + - CREATE + resources: + - votes + - subscriptions + - submissions + - securityreports + - feedbackprofiles + sideEffects: None +- admissionReviewVersions: + - v1 + clientConfig: + service: + name: webhook-service + namespace: system + path: /mutate-submissionreview + failurePolicy: Fail + name: reviewer.feedback.miloapis.com + rules: + - apiGroups: + - feedback.miloapis.com + apiVersions: + - v1alpha1 + operations: + - CREATE + - UPDATE + resources: + - submissionreviews + sideEffects: None diff --git a/go.mod b/go.mod index cc87fb8..7c3f1b3 100644 --- a/go.mod +++ b/go.mod @@ -5,10 +5,13 @@ go 1.27.0 toolchain go1.27.4 require ( + github.com/evanphx/json-patch/v5 v5.9.11 github.com/spf13/cobra v1.10.2 + k8s.io/api v0.37.2 k8s.io/apimachinery v0.37.2 k8s.io/client-go v0.37.2 sigs.k8s.io/controller-runtime v0.25.3 + sigs.k8s.io/yaml v1.6.0 ) require ( @@ -16,7 +19,6 @@ require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-logr/logr v1.4.4 // indirect @@ -68,7 +70,6 @@ require ( google.golang.org/protobuf v1.36.12 // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/api v0.37.2 // indirect k8s.io/apiextensions-apiserver v0.37.0 // indirect k8s.io/code-generator v0.37.2 // indirect k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3 // indirect @@ -78,7 +79,6 @@ require ( sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect ) tool k8s.io/code-generator diff --git a/internal/identity/identity.go b/internal/identity/identity.go new file mode 100644 index 0000000..33f75b1 --- /dev/null +++ b/internal/identity/identity.go @@ -0,0 +1,84 @@ +// Package identity reads who is making a request, from the user info Milo +// passes to admission webhooks. +package identity + +import ( + "strings" + + authenticationv1 "k8s.io/api/authentication/v1" +) + +// Usernames of the service's own components in Milo: the common names of +// the client certificates they present. +const ( + OperatorUser = "system:feedback-operator@feedback.miloapis.com" + SyncUser = "system:feedback-sync@feedback.miloapis.com" + UploadsUser = "system:feedback-uploads@feedback.miloapis.com" +) + +// Keys Milo sets in user extras. +const ( + ParentKindExtraKey = "iam.miloapis.com/parent-type" + ParentNameExtraKey = "iam.miloapis.com/parent-name" + EmailVerifiedExtraKey = "iam.miloapis.com/emailVerified" +) + +// ParentKindUser is the parent kind of requests in a user's own context. +const ParentKindUser = "User" + +// Caller is who a request comes from, as the feedback rules see it. +type Caller int + +const ( + // Other is anyone else: staff, the website, users. + Other Caller = iota + Operator + Sync + Uploads +) + +// Of returns the caller for u. +func Of(u authenticationv1.UserInfo) Caller { + switch u.Username { + case OperatorUser: + return Operator + case SyncUser: + return Sync + case UploadsUser: + return Uploads + } + return Other +} + +// User returns the user whose own context the request was made in, if it +// was made in one. +func User(u authenticationv1.UserInfo) (string, bool) { + if !strings.EqualFold(extra(u, ParentKindExtraKey), ParentKindUser) { + return "", false + } + name := extra(u, ParentNameExtraKey) + return name, name != "" +} + +// EmailUnverified reports whether the caller is a person whose email address +// isn't verified. Milo's identity provider sets the key on every human, "true" +// or "false"; machine identities don't carry it and pass, as in Milo's own +// admission plugin. +func EmailUnverified(u authenticationv1.UserInfo) bool { + for k, vals := range u.Extra { + if strings.EqualFold(k, EmailVerifiedExtraKey) { + return !(len(vals) == 1 && vals[0] == "true") + } + } + return false +} + +// extra returns the single value of key, matched case-insensitively. +func extra(u authenticationv1.UserInfo, key string) string { + for k, vals := range u.Extra { + if strings.EqualFold(k, key) && len(vals) == 1 { + return vals[0] + } + } + return "" +} diff --git a/internal/identity/identity_test.go b/internal/identity/identity_test.go new file mode 100644 index 0000000..5418e93 --- /dev/null +++ b/internal/identity/identity_test.go @@ -0,0 +1,54 @@ +package identity + +import ( + "testing" + + authenticationv1 "k8s.io/api/authentication/v1" +) + +func TestUser(t *testing.T) { + for _, tc := range []struct { + extra map[string]authenticationv1.ExtraValue + want string + wantOK bool + }{ + {map[string]authenticationv1.ExtraValue{ParentKindExtraKey: {"User"}, ParentNameExtraKey: {"u1"}}, "u1", true}, + // Keys can arrive lower-cased. + {map[string]authenticationv1.ExtraValue{"iam.miloapis.com/parent-type": {"user"}, "IAM.miloapis.com/Parent-Name": {"u1"}}, "u1", true}, + {map[string]authenticationv1.ExtraValue{ParentKindExtraKey: {"Organization"}, ParentNameExtraKey: {"o1"}}, "", false}, + {map[string]authenticationv1.ExtraValue{ParentKindExtraKey: {"User"}}, "", false}, + {nil, "", false}, + } { + got, ok := User(authenticationv1.UserInfo{Extra: tc.extra}) + if got != tc.want || ok != tc.wantOK { + t.Errorf("User(%v) = %q, %v; want %q, %v", tc.extra, got, ok, tc.want, tc.wantOK) + } + } +} + +func TestEmailUnverified(t *testing.T) { + for _, tc := range []struct { + vals []string + set bool + want bool + }{ + {[]string{"true"}, true, false}, + {[]string{"false"}, true, true}, + {[]string{""}, true, true}, + {nil, false, false}, // machines carry no verdict + } { + u := authenticationv1.UserInfo{} + if tc.set { + u.Extra = map[string]authenticationv1.ExtraValue{EmailVerifiedExtraKey: tc.vals} + } + if got := EmailUnverified(u); got != tc.want { + t.Errorf("EmailUnverified(%v) = %v, want %v", tc.vals, got, tc.want) + } + } +} + +func TestOf(t *testing.T) { + if Of(authenticationv1.UserInfo{Username: OperatorUser}) != Operator || Of(authenticationv1.UserInfo{Username: "x"}) != Other { + t.Error("Of misreads callers") + } +} diff --git a/internal/webhook/envtest_test.go b/internal/webhook/envtest_test.go new file mode 100644 index 0000000..9fb3b36 --- /dev/null +++ b/internal/webhook/envtest_test.go @@ -0,0 +1,136 @@ +package webhook + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/rest" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook" + + "go.miloapis.com/feedback/internal/identity" + v1 "go.miloapis.com/feedback/pkg/apis/feedback/v1alpha1" +) + +// TestWebhooksInFrontOfAnAPIServer installs the CRDs and the generated +// webhook config in an envtest API server, serves the webhooks, and makes +// requests as users in their own context. It checks the mutation and the +// CRDs' own rules work together: the vote name rule runs after the owner is +// set. +func TestWebhooksInFrontOfAnAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS not set; run with task test") + } + scheme := runtime.NewScheme() + if err := v1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + env := &envtest.Environment{ + CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "crd", "bases")}, + ErrorIfCRDPathMissing: true, + WebhookInstallOptions: envtest.WebhookInstallOptions{ + Paths: []string{filepath.Join("..", "..", "config", "milo", "webhook", "manifests.yaml")}, + }, + } + cfg, err := env.Start() + if err != nil { + t.Fatalf("start API server: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + + o := env.WebhookInstallOptions + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ + Scheme: scheme, + Metrics: metricsserver.Options{BindAddress: "0"}, + WebhookServer: ctrlwebhook.NewServer(ctrlwebhook.Options{ + Host: o.LocalServingHost, Port: o.LocalServingPort, CertDir: o.LocalServingCertDir, + }), + }) + if err != nil { + t.Fatal(err) + } + Register(mgr) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go func() { _ = mgr.Start(ctx) }() + waitForWebhooks(t, mgr) + + as := func(user string, extra map[string][]string) client.Client { + c := rest.CopyConfig(cfg) + c.Impersonate = rest.ImpersonationConfig{UserName: user, Groups: []string{"system:masters"}, Extra: extra} + cl, err := client.New(c, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return cl + } + ada := as("ada@example.com", map[string][]string{identity.ParentKindExtraKey: {"User"}, identity.ParentNameExtraKey: {"u1"}}) + staff := as("staff@datum.net", nil) + + vote := func(name, owner string) *v1.Vote { + return &v1.Vote{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: v1.VoteSpec{PostRef: v1.PostReference{Name: "p1"}, UserRef: v1.UserReference{Name: owner}}, + } + } + + t.Run("the caller becomes the owner", func(t *testing.T) { + v := vote("p1.u1", "") + if err := ada.Create(ctx, v); err != nil { + t.Fatal(err) + } + if v.Spec.UserRef.Name != "u1" { + t.Errorf("owner = %q", v.Spec.UserRef.Name) + } + }) + + t.Run("someone else's name is replaced, so the name rule fails", func(t *testing.T) { + err := ada.Create(ctx, vote("p1.u2", "u2")) + if !apierrors.IsInvalid(err) || !strings.Contains(err.Error(), "metadata.name must be") { + t.Errorf("err = %v", err) + } + }) + + t.Run("staff can't vote for users", func(t *testing.T) { + if err := staff.Create(ctx, vote("p1.u3", "u3")); !apierrors.IsForbidden(err) { + t.Errorf("err = %v, want Forbidden", err) + } + }) + + t.Run("the reviewer is recorded", func(t *testing.T) { + r := &v1.SubmissionReview{ObjectMeta: metav1.ObjectMeta{Name: "sub-1"}} + if err := staff.Create(ctx, r); err != nil { + t.Fatal(err) + } + r.Spec = v1.SubmissionReviewSpec{Decision: v1.ReviewDecisionRejected, Reason: "dup", Reviewer: "someone-else"} + if err := staff.Update(ctx, r); err != nil { + t.Fatal(err) + } + if r.Spec.Reviewer != "staff@datum.net" || r.Spec.ReviewedAt == nil { + t.Errorf("reviewer %q at %v", r.Spec.Reviewer, r.Spec.ReviewedAt) + } + }) +} + +// waitForWebhooks waits until the webhook server answers. +func waitForWebhooks(t *testing.T, mgr ctrl.Manager) { + t.Helper() + check := mgr.GetWebhookServer().StartedChecker() + deadline := time.Now().Add(20 * time.Second) + for check(nil) != nil { + if time.Now().After(deadline) { + t.Fatal("webhook server didn't start") + } + time.Sleep(100 * time.Millisecond) + } +} diff --git a/internal/webhook/owner.go b/internal/webhook/owner.go new file mode 100644 index 0000000..27046bd --- /dev/null +++ b/internal/webhook/owner.go @@ -0,0 +1,81 @@ +// Package webhook holds the operator's admission webhooks, which Milo calls +// for feedback resources. +package webhook + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + + admissionv1 "k8s.io/api/admission/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "go.miloapis.com/feedback/internal/identity" +) + +// +kubebuilder:webhook:path=/mutate-owner,mutating=true,failurePolicy=fail,sideEffects=None,groups=feedback.miloapis.com,resources=votes;subscriptions;submissions;securityreports;feedbackprofiles,verbs=create,versions=v1alpha1,name=owner.feedback.miloapis.com,admissionReviewVersions=v1 + +// Owner sets spec.userRef on user-owned resources from the request, so no +// client can create one for someone else. Milo limits what each user sees by +// that field. +// +// - In a user's own context, spec.userRef is that user, whatever the client +// sent. +// - The operator creates them for users in the platform context (a vote for +// an approved submitter, a report moved from a submission) and names the +// owner itself. +// - The Security Team logs reports for people without an account in the +// platform context, with no owner. +// +// Anything else is refused. Updates can't change spec.userRef: the CRDs make +// it immutable. +type Owner struct{} + +var _ admission.Handler = Owner{} + +// Handle implements admission.Handler. +func (Owner) Handle(_ context.Context, req admission.Request) admission.Response { + if req.Operation != admissionv1.Create { + return admission.Allowed("") + } + obj := &unstructured.Unstructured{} + if err := json.Unmarshal(req.Object.Raw, &obj.Object); err != nil { + return admission.Errored(http.StatusBadRequest, err) + } + owner, _, _ := unstructured.NestedString(obj.Object, "spec", "userRef", "name") + resource := req.Resource.Resource + + if user, ok := identity.User(req.UserInfo); ok { + if owner == user { + return admission.Allowed("") + } + if err := unstructured.SetNestedField(obj.Object, user, "spec", "userRef", "name"); err != nil { + return admission.Errored(http.StatusInternalServerError, err) + } + return patch(req, obj) + } + + switch { + case identity.Of(req.UserInfo) == identity.Operator: + if owner == "" && resource != "securityreports" { + return admission.Denied("spec.userRef.name is required") + } + return admission.Allowed("") + case resource == "securityreports" && owner == "": + // The Security Team logging a report from email or GitHub. + return admission.Allowed("") + case resource == "securityreports": + return admission.Denied("in the platform context, reports are logged for external reporters only: leave spec.userRef empty and set spec.reporter") + } + return admission.Denied(fmt.Sprintf("%s are created by users in their own context", resource)) +} + +func patch(req admission.Request, obj *unstructured.Unstructured) admission.Response { + raw, err := json.Marshal(obj.Object) + if err != nil { + return admission.Errored(http.StatusInternalServerError, err) + } + return admission.PatchResponseFromRaw(req.Object.Raw, raw) +} diff --git a/internal/webhook/register.go b/internal/webhook/register.go new file mode 100644 index 0000000..f55c5a0 --- /dev/null +++ b/internal/webhook/register.go @@ -0,0 +1,13 @@ +package webhook + +import ( + "sigs.k8s.io/controller-runtime/pkg/manager" + "sigs.k8s.io/controller-runtime/pkg/webhook" +) + +// Register adds every admission webhook to mgr's webhook server. +func Register(mgr manager.Manager) { + s := mgr.GetWebhookServer() + s.Register("/mutate-owner", &webhook.Admission{Handler: Owner{}}) + s.Register("/mutate-submissionreview", &webhook.Admission{Handler: Reviewer{}}) +} diff --git a/internal/webhook/review.go b/internal/webhook/review.go new file mode 100644 index 0000000..d4b98b2 --- /dev/null +++ b/internal/webhook/review.go @@ -0,0 +1,70 @@ +package webhook + +import ( + "context" + "encoding/json" + "net/http" + "time" + + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + v1 "go.miloapis.com/feedback/pkg/apis/feedback/v1alpha1" +) + +// +kubebuilder:webhook:path=/mutate-submissionreview,mutating=true,failurePolicy=fail,sideEffects=None,groups=feedback.miloapis.com,resources=submissionreviews,verbs=create;update,versions=v1alpha1,name=reviewer.feedback.miloapis.com,admissionReviewVersions=v1 + +// Reviewer records who decided on a submission. When a request sets +// spec.decision, it sets spec.reviewer and spec.reviewedAt from the request; +// while there is no decision it clears them, so a client can't name someone +// else. After that the CRD keeps the whole spec immutable. +type Reviewer struct { + // Now returns the current time; tests replace it. + Now func() time.Time +} + +var _ admission.Handler = Reviewer{} + +// Handle implements admission.Handler. +func (r Reviewer) Handle(_ context.Context, req admission.Request) admission.Response { + review := &v1.SubmissionReview{} + if err := json.Unmarshal(req.Object.Raw, review); err != nil { + return admission.Errored(http.StatusBadRequest, err) + } + var oldDecision v1.ReviewDecision + if req.Operation == admissionv1.Update { + old := &v1.SubmissionReview{} + if err := json.Unmarshal(req.OldObject.Raw, old); err != nil { + return admission.Errored(http.StatusBadRequest, err) + } + oldDecision = old.Spec.Decision + } + + s := &review.Spec + switch { + case oldDecision != "": + // Decided already; the CRD rejects any change. + return admission.Allowed("") + case s.Decision == "": + if s.Reviewer == "" && s.ReviewedAt == nil { + return admission.Allowed("") + } + s.Reviewer, s.ReviewedAt = "", nil + default: + now := metav1.NewTime(r.now().UTC().Truncate(time.Second)) + s.Reviewer, s.ReviewedAt = req.UserInfo.Username, &now + } + raw, err := json.Marshal(review) + if err != nil { + return admission.Errored(http.StatusInternalServerError, err) + } + return admission.PatchResponseFromRaw(req.Object.Raw, raw) +} + +func (r Reviewer) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} diff --git a/internal/webhook/webhook_test.go b/internal/webhook/webhook_test.go new file mode 100644 index 0000000..9c5cd70 --- /dev/null +++ b/internal/webhook/webhook_test.go @@ -0,0 +1,169 @@ +package webhook + +import ( + "context" + "encoding/json" + "testing" + "time" + + jsonpatch "github.com/evanphx/json-patch/v5" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "go.miloapis.com/feedback/internal/identity" + v1 "go.miloapis.com/feedback/pkg/apis/feedback/v1alpha1" +) + +func inUserContext(id string) authenticationv1.UserInfo { + return authenticationv1.UserInfo{Username: "ada@example.com", Extra: map[string]authenticationv1.ExtraValue{ + identity.ParentKindExtraKey: {"User"}, + identity.ParentNameExtraKey: {id}, + }} +} + +func request(t *testing.T, op admissionv1.Operation, resource string, user authenticationv1.UserInfo, obj, old runtime.Object) admission.Request { + t.Helper() + raw := func(o runtime.Object) runtime.RawExtension { + if o == nil { + return runtime.RawExtension{} + } + b, err := json.Marshal(o) + if err != nil { + t.Fatal(err) + } + return runtime.RawExtension{Raw: b} + } + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: op, + Resource: metav1.GroupVersionResource{Group: v1.GroupName, Version: "v1alpha1", Resource: resource}, + UserInfo: user, + Object: raw(obj), + OldObject: raw(old), + }} +} + +// patched applies resp's patches to the request object. +func patched(t *testing.T, req admission.Request, resp admission.Response, into any) { + t.Helper() + ops, err := json.Marshal(resp.Patches) + if err != nil { + t.Fatal(err) + } + p, err := jsonpatch.DecodePatch(ops) + if err != nil { + t.Fatal(err) + } + out, err := p.Apply(req.Object.Raw) + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(out, into); err != nil { + t.Fatal(err) + } +} + +func vote(owner string) *v1.Vote { + return &v1.Vote{ + TypeMeta: metav1.TypeMeta{APIVersion: v1.SchemeGroupVersion.String(), Kind: "Vote"}, + ObjectMeta: metav1.ObjectMeta{Name: v1.OwnedName("p", "u1")}, + Spec: v1.VoteSpec{PostRef: v1.PostReference{Name: "p"}, UserRef: v1.UserReference{Name: owner}}, + } +} + +func TestOwnerSetsTheCallerInTheUserContext(t *testing.T) { + for _, sent := range []string{"", "someone-else"} { + req := request(t, admissionv1.Create, "votes", inUserContext("u1"), vote(sent), nil) + resp := Owner{}.Handle(context.Background(), req) + if !resp.Allowed { + t.Fatalf("sent %q: denied: %v", sent, resp.Result) + } + var got v1.Vote + patched(t, req, resp, &got) + if got.Spec.UserRef.Name != "u1" { + t.Errorf("sent %q: owner = %q, want u1", sent, got.Spec.UserRef.Name) + } + } + + req := request(t, admissionv1.Create, "votes", inUserContext("u1"), vote("u1"), nil) + if resp := (Owner{}).Handle(context.Background(), req); !resp.Allowed || len(resp.Patches) != 0 { + t.Errorf("already the caller: allowed %v, %d patches", resp.Allowed, len(resp.Patches)) + } +} + +func TestOwnerOutsideTheUserContext(t *testing.T) { + staff := authenticationv1.UserInfo{Username: "staff@datum.net"} + operator := authenticationv1.UserInfo{Username: identity.OperatorUser} + report := func(owner string) *v1.SecurityReport { + r := &v1.SecurityReport{Spec: v1.SecurityReportSpec{Title: "t", Description: "d"}} + if owner != "" { + r.Spec.UserRef = &v1.UserReference{Name: owner} + } + return r + } + for _, tc := range []struct { + name string + resource string + user authenticationv1.UserInfo + obj runtime.Object + allowed bool + }{ + {"staff can't vote for someone", "votes", staff, vote("u1"), false}, + {"staff can't vote", "votes", staff, vote(""), false}, + {"operator votes for a user", "votes", operator, vote("u1"), true}, + {"operator must name the owner", "votes", operator, vote(""), false}, + {"staff log an external report", "securityreports", staff, report(""), true}, + {"staff can't own a report for someone", "securityreports", staff, report("u1"), false}, + {"operator moves a report for a user", "securityreports", operator, report("u1"), true}, + } { + t.Run(tc.name, func(t *testing.T) { + resp := Owner{}.Handle(context.Background(), request(t, admissionv1.Create, tc.resource, tc.user, tc.obj, nil)) + if resp.Allowed != tc.allowed { + t.Errorf("allowed = %v, want %v (%v)", resp.Allowed, tc.allowed, resp.Result) + } + }) + } +} + +func TestOwnerIgnoresUpdates(t *testing.T) { + req := request(t, admissionv1.Update, "votes", authenticationv1.UserInfo{Username: "x"}, vote("u2"), vote("u1")) + if resp := (Owner{}).Handle(context.Background(), req); !resp.Allowed || len(resp.Patches) != 0 { + t.Errorf("update: allowed %v, %d patches", resp.Allowed, len(resp.Patches)) + } +} + +func TestReviewerRecordsWhoDecided(t *testing.T) { + now := time.Date(2026, 11, 17, 10, 0, 0, 0, time.UTC) + r := Reviewer{Now: func() time.Time { return now }} + staff := authenticationv1.UserInfo{Username: "staff@datum.net"} + review := func(decision v1.ReviewDecision, reviewer string) *v1.SubmissionReview { + return &v1.SubmissionReview{ + ObjectMeta: metav1.ObjectMeta{Name: "sub-1"}, + Spec: v1.SubmissionReviewSpec{Decision: decision, Reason: "x", Reviewer: reviewer}, + } + } + + req := request(t, admissionv1.Update, "submissionreviews", staff, review(v1.ReviewDecisionRejected, "someone-else"), review("", "")) + resp := r.Handle(context.Background(), req) + var got v1.SubmissionReview + patched(t, req, resp, &got) + if got.Spec.Reviewer != "staff@datum.net" || got.Spec.ReviewedAt == nil || !got.Spec.ReviewedAt.Time.Equal(now) { + t.Errorf("decided: reviewer %q at %v", got.Spec.Reviewer, got.Spec.ReviewedAt) + } + + req = request(t, admissionv1.Update, "submissionreviews", staff, review("", "someone-else"), review("", "")) + resp = r.Handle(context.Background(), req) + got = v1.SubmissionReview{} + patched(t, req, resp, &got) + if got.Spec.Reviewer != "" { + t.Errorf("undecided: reviewer %q kept", got.Spec.Reviewer) + } + + // Already decided: left to the CRD's immutability rule. + req = request(t, admissionv1.Update, "submissionreviews", staff, review(v1.ReviewDecisionRejected, "a"), review(v1.ReviewDecisionRejected, "a")) + if resp := r.Handle(context.Background(), req); !resp.Allowed || len(resp.Patches) != 0 { + t.Errorf("decided earlier: allowed %v, %d patches", resp.Allowed, len(resp.Patches)) + } +} diff --git a/test/config/milo_test.go b/test/config/milo_test.go new file mode 100644 index 0000000..8726467 --- /dev/null +++ b/test/config/milo_test.go @@ -0,0 +1,257 @@ +// Package config checks the manifests under config/ against the CRDs and +// each other. +package config + +import ( + "bytes" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "sigs.k8s.io/yaml" + + "go.miloapis.com/feedback/internal/identity" + v1 "go.miloapis.com/feedback/pkg/apis/feedback/v1alpha1" +) + +const group = v1.GroupName + +type obj map[string]any + +func (o obj) get(path ...string) any { + var cur any = map[string]any(o) + for _, p := range path { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = m[p] + } + return cur +} + +func (o obj) str(path ...string) string { s, _ := o.get(path...).(string); return s } +func (o obj) list(path ...string) []any { l, _ := o.get(path...).([]any); return l } + +// load reads every object in the YAML files under dir. +func load(t *testing.T, dir string) []obj { + t.Helper() + var out []obj + err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error { + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".yaml") || d.Name() == "kustomization.yaml" { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + for _, doc := range bytes.Split(data, []byte("\n---\n")) { + var o obj + if err := yaml.Unmarshal(doc, &o); err != nil { + t.Fatalf("%s: %v", path, err) + } + if len(o) > 0 { + out = append(out, o) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +func ofKind(objs []obj, kind string) []obj { + var out []obj + for _, o := range objs { + if o.str("kind") == kind { + out = append(out, o) + } + } + return out +} + +type crd struct { + kind, plural string + contexts []string + ownerField string + hiddenField string + status bool +} + +func loadCRDs(t *testing.T) map[string]crd { + t.Helper() + out := map[string]crd{} + for _, c := range ofKind(load(t, "../../config/crd/bases"), "CustomResourceDefinition") { + ann := func(k string) string { return c.str("metadata", "annotations", k) } + status := false + for _, v := range c.list("spec", "versions") { + if obj(v.(map[string]any)).get("subresources", "status") != nil { + status = true + } + } + out[c.str("spec", "names", "plural")] = crd{ + kind: c.str("spec", "names", "kind"), + plural: c.str("spec", "names", "plural"), + contexts: strings.Split(ann(v1.ParentContextsAnnotation), ";"), + ownerField: ann(v1.OwnerFieldAnnotation), + hiddenField: ann(v1.HiddenFieldAnnotation), + status: status, + } + } + if len(out) == 0 { + t.Fatal("no CRDs found") + } + return out +} + +func TestMiloConfig(t *testing.T) { + crds := loadCRDs(t) + objs := load(t, "../../config/milo") + + // perms["posts"] = {"get", ...}; perms["posts/status"] = {...} + perms := map[string][]string{} + kinds := map[string]string{} // kind -> plural + for _, pr := range ofKind(objs, "ProtectedResource") { + plural := pr.str("spec", "plural") + c, ok := crds[plural] + if !ok { + t.Errorf("ProtectedResource for %s has no CRD", plural) + continue + } + if pr.str("spec", "kind") != c.kind { + t.Errorf("ProtectedResource %s: kind %s, CRD says %s", plural, pr.str("spec", "kind"), c.kind) + } + kinds[c.kind] = plural + for _, v := range pr.list("spec", "permissions") { + perms[plural] = append(perms[plural], v.(string)) + } + subs := map[string]bool{} + for _, s := range pr.list("spec", "subresources") { + so := obj(s.(map[string]any)) + subs[so.str("name")] = true + for _, v := range so.list("permissions") { + perms[plural+"/"+so.str("name")] = append(perms[plural+"/"+so.str("name")], v.(string)) + } + } + if subs["status"] != c.status { + t.Errorf("%s: status subresource declared %v, CRD has it %v", plural, subs["status"], c.status) + } + if subs["hidden"] != (c.hiddenField != "") { + t.Errorf("%s: hidden subresource declared %v, CRD hidden field %q", plural, subs["hidden"], c.hiddenField) + } + userParent := slices.ContainsFunc(pr.list("spec", "parentResources"), func(p any) bool { + return obj(p.(map[string]any)).str("kind") == "User" + }) + if userParent != slices.Contains(c.contexts, "User") { + t.Errorf("%s: User parent %v, but CRD contexts are %v", plural, userParent, c.contexts) + } + } + for plural := range crds { + if _, ok := perms[plural]; !ok { + t.Errorf("no ProtectedResource for %s", plural) + } + } + + allows := func(resource, verb string) bool { return slices.Contains(perms[resource], verb) } + roles := map[string]bool{} + for _, r := range ofKind(objs, "Role") { + roles[r.str("metadata", "name")] = true + } + for _, r := range ofKind(objs, "Role") { + name := r.str("metadata", "name") + for _, p := range r.list("spec", "includedPermissions") { + s := p.(string) + rest, ok := strings.CutPrefix(s, group+"/") + i := strings.LastIndex(rest, ".") + if !ok || i < 0 || !allows(rest[:i], rest[i+1:]) { + t.Errorf("role %s: %s isn't a declared permission", name, s) + } + // Security reports and their triage stay with the Security Team, + // and reporters' own reports with the user role. + secret := strings.HasPrefix(rest, "securityreports") || strings.HasPrefix(rest, "securityreporttriages") + if secret && name != group+"-security-team" && !(name == group+"-user" && strings.HasPrefix(rest, "securityreports.")) { + t.Errorf("role %s grants %s", name, s) + } + } + for _, in := range r.list("spec", "inheritedRoles") { + if n := obj(in.(map[string]any)).str("name"); !roles[n] { + t.Errorf("role %s inherits unknown role %s", name, n) + } + } + } + + for _, cr := range ofKind(objs, "ClusterRole") { + for _, rule := range cr.list("rules") { + ro := obj(rule.(map[string]any)) + if !slices.Contains(ro.list("apiGroups"), any(group)) { + continue + } + for _, res := range ro.list("resources") { + for _, v := range ro.list("verbs") { + if !allows(res.(string), v.(string)) { + t.Errorf("ClusterRole %s grants %s %s, which isn't declared", cr.str("metadata", "name"), v, res) + } + } + } + } + } + subjects := map[string]bool{} + for _, b := range ofKind(objs, "ClusterRoleBinding") { + for _, s := range b.list("subjects") { + subjects[obj(s.(map[string]any)).str("name")] = true + } + } + for _, u := range []string{identity.OperatorUser, identity.SyncUser, identity.UploadsUser} { + if !subjects[u] { + t.Errorf("no ClusterRoleBinding for %s", u) + } + } + + for _, b := range ofKind(objs, "PolicyBinding") { + if n := b.str("spec", "roleRef", "name"); !roles[n] { + t.Errorf("PolicyBinding %s binds unknown role %s", b.str("metadata", "name"), n) + } + if k := b.str("spec", "resourceSelector", "resourceKind", "kind"); kinds[k] == "" { + t.Errorf("PolicyBinding %s selects unknown kind %s", b.str("metadata", "name"), k) + } + } +} + +// TestOwnerWebhookCoversOwnedKinds checks the owner webhook runs for exactly +// the CRDs Milo limits by owner, so no user-owned kind can be created with +// someone else's name in it. +func TestOwnerWebhookCoversOwnedKinds(t *testing.T) { + crds := loadCRDs(t) + var owned []string + for plural, c := range crds { + if c.ownerField != "" { + if c.ownerField != "spec.userRef.name" { + t.Errorf("%s: owner field %s; the webhook sets spec.userRef.name", plural, c.ownerField) + } + owned = append(owned, plural) + } + } + var covered []string + for _, m := range ofKind(load(t, "../../config/milo/webhook"), "MutatingWebhookConfiguration") { + for _, w := range m.list("webhooks") { + wo := obj(w.(map[string]any)) + if wo.str("name") != "owner.feedback.miloapis.com" { + continue + } + for _, r := range wo.list("rules") { + for _, res := range obj(r.(map[string]any)).list("resources") { + covered = append(covered, res.(string)) + } + } + } + } + slices.Sort(owned) + slices.Sort(covered) + if !slices.Equal(owned, covered) { + t.Errorf("owner webhook covers %v, owned kinds are %v", covered, owned) + } +}