apiVersion: platform.kratix.io/v1alpha1
kind: Promise
metadata:
  name: secure-repo
spec:
  api:
    apiVersion: apiextensions.k8s.io/v1
    kind: CustomResourceDefinition
    metadata:
      name: securerepos.example.kratix.io
    spec:
      group: example.kratix.io
      names:
        kind: SecureRepo
        plural: securerepos
        singular: securerepo
      scope: Namespaced
      versions:
        - name: v1alpha1
          served: true
          storage: true
          schema:
            openAPIV3Schema:
              type: object
              properties:
                spec:
                  type: object
                  properties:
                    repo:
                      type: string
                      description: Repository to onboard to the security baseline.
                    language:
                      type: string
                      description: Primary language, e.g. go, node or python.
                    securityContact:
                      type: string
                      description: Where to report vulnerabilities (email or Slack).
                    scanSchedule:
                      type: string
                      description: How often to scan - daily or weekly. Defaults to weekly.
                  required:
                    - repo
                    - language
                    - securityContact
  workflows:
    resource:
      configure:
        - apiVersion: platform.kratix.io/v1alpha1
          kind: Pipeline
          metadata:
            name: configure
          spec:
            rbac:
              permissions:
                # resourceNamespace "*" makes Kratix grant these as a ClusterRole
                # bound with a ClusterRoleBinding, which is required to manage the
                # cluster-scoped GitStateStore and Destination resources.
                - resourceNamespace: "*"
                  apiGroups: ["platform.kratix.io"]
                  resources: ["gitstatestores", "destinations"]
                  verbs: ["get", "create", "update", "patch"]
            containers:
              - name: configure
                image: ghcr.io/syntasso/kratix-pipeline-utility:v0.0.4
                envFrom:
                  - secretRef:
                      name: gitea-credentials
                env:
                  - name: GITEA_BASE_URL
                    value: https://gitea-http.gitea.svc.cluster.local/gitea_admin
                command:
                  - python3
                  - -c
                  - |
                    import os, subprocess
                    from textwrap import dedent
                    import kratix_sdk as ks

                    sdk = ks.KratixSDK()
                    spec = sdk.read_resource_input()
                    repo = spec.get_value("spec.repo")
                    language = spec.get_value("spec.language")
                    contact = spec.get_value("spec.securityContact")
                    schedule = spec.get_value("spec.scanSchedule", default="weekly")
                    cron = {"daily": "0 0 * * *", "weekly": "0 0 * * 1"}.get(schedule, "0 0 * * 1")
                    url = f"{os.environ['GITEA_BASE_URL']}/{repo}"

                    # Create a GitStateStore and Destination pointing at the user's repo.
                    subprocess.run(["kubectl", "apply", "-f", "-"], check=True, input=dedent(f"""
                        apiVersion: platform.kratix.io/v1alpha1
                        kind: GitStateStore
                        metadata:
                          name: secure-{repo}
                        spec:
                          url: {url}
                          branch: main
                          secretRef:
                            name: gitea-credentials
                            namespace: default
                        ---
                        apiVersion: platform.kratix.io/v1alpha1
                        kind: Destination
                        metadata:
                          name: secure-{repo}
                          labels:
                            repo: {repo}
                        spec:
                          path: "."
                          filepath: {{ mode: none }}
                          strictMatchLabels: true
                          initWorkloads: {{ enabled: false }}
                          stateStoreRef:
                            name: secure-{repo}
                            kind: GitStateStore
                    """).encode())

                    # Platform-owned security baseline: a policy at the repo root
                    # and a scan workflow under .github/workflows.
                    security_md = dedent(f"""\
                        # Security Policy

                        Report vulnerabilities to {contact}.
                        We aim to respond within 3 working days.

                        _Managed by the platform - do not edit._
                    """)

                    scan_workflow = dedent(f"""\
                        # Managed by the platform - do not edit.
                        name: security-scan
                        on:
                          pull_request:
                          schedule:
                            - cron: "{cron}"
                        jobs:
                          scan:
                            runs-on: ubuntu-latest
                            steps:
                              - uses: actions/checkout@v4
                              - run: echo "TODO run {language} security scan"
                    """)

                    sdk.write_output("SECURITY.md", security_md.encode())
                    sdk.write_output(".github/workflows/security.yml", scan_workflow.encode())
                    sdk.write_destination_selectors([ks.DestinationSelector(match_labels={"repo": repo})])
