name: KBS e2e (Docker Compose and Sample TEE)

on:
  pull_request:
    branches: 
      - main

env:
  TEST_SECRET_CONTENT: shhhhh
  TEST_SECRET_PATH: test-org/test-repo/test-secret

jobs:
  e2e-test:
    runs-on: ubuntu-latest
    env:
      RUSTC_VERSION: 1.85.0
    steps:
    - name: Checkout KBS
      uses: actions/checkout@v4

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v3

    - name: Cache Docker layers
      uses: actions/cache@v3
      with:
        path: /tmp/.buildx-cache
        key: ${{ runner.os }}-buildx-${{ github.sha }}
        restore-keys: |
          ${{ runner.os }}-buildx-

    - name: Create cache directory
      run: mkdir -p /tmp/.buildx-cache

    - name: Install Rust ${{ env.RUSTC_VERSION }} (for client)
      run: |
        rustup update --no-self-update ${{ env.RUSTC_VERSION }}
        rustup component add --toolchain ${{ env.RUSTC_VERSION }} rustc
        rustup default ${{ env.RUSTC_VERSION }}

    - name: Build client
      run: |
        cargo build --manifest-path tools/kbs-client/Cargo.toml --no-default-features --features sample_only --release

    - name: Setup Keys
      run: | 
        openssl genpkey -algorithm ed25519 > kbs/config/private.key
        openssl pkey -in kbs/config/private.key -pubout -out kbs/config/public.pub

    - name: Clean Docker System
      run: |
        docker system prune -af
        docker volume prune -f

    - name: Build KBS Cluster
      run: |
        DOCKER_BUILDKIT=1 docker compose build --build-arg BUILDKIT_INLINE_CACHE=1

    - name: Start KBS cluster
      run: docker compose up -d

    - name: Set Resource
      working-directory: target/release/
      run: |
        echo "$TEST_SECRET_CONTENT" > test-secret
        ./kbs-client --url http://127.0.0.1:8080 config --auth-private-key ../../kbs/config/private.key  set-resource --path "$TEST_SECRET_PATH" --resource-file test-secret

    - name: Update policy (negative)
      working-directory: target/release/
      run: ./kbs-client --url http://127.0.0.1:8080 config --auth-private-key ../../kbs/config/private.key  set-resource-policy --policy-file "$policy_path"
      env:
        policy_path: ../../kbs/test/data/policy_3.rego
  
    - name: Get Resource (negative)
      working-directory: target/release/
      run: |
        ! ./kbs-client --url http://127.0.0.1:8080 get-resource --path "$TEST_SECRET_PATH"

    - name: Update policy
      working-directory: target/release/
      run: ./kbs-client --url http://127.0.0.1:8080 config --auth-private-key ../../kbs/config/private.key  set-resource-policy --policy-file "$policy_path"
      env:
        policy_path: ../../kbs/test/data/policy_2.rego

    - name: Get Resource
      working-directory: target/release/
      run: ./kbs-client --url http://127.0.0.1:8080 get-resource --path "$TEST_SECRET_PATH"
