# Bitbucket PipelinesでのDevice Protection

Bitbucket PipelinesのステップはLinux上で実行されるため、Device Protectionは他のLinuxマシンと同じ方法でインストールします。Bitbucket特有なのはインストール先です。常駐するLinux Shell runnerには一度だけインストールし、Bitbucket CloudおよびDocker runnerでは各ステップ内でインストールします。

トークンとインストール方式については、まず[Linux向けDevice Protectionのインストール](https://help.aikidogov.us/docs/docs-ja/aikido-device-protection/deploying-aikido-endpoint/device-protection-mdm-guides/linux/install-device-protection-for-linux)をお読みください。以下のジョブレベルのスニペットではコンテナ方式を使用しています。コンテナ方式については[コンテナでのDevice Protection](https://help.aikidogov.us/docs/docs-ja/aikido-device-protection/deploying-aikido-endpoint/device-protection-mdm-guides/linux/device-protection-in-containers)で説明しています。

## Bitbucket CloudとDocker runner

Device Protectionのトークンを、`AIKIDO_TOKEN`という名前のセキュアなリポジトリ変数として追加します。次に、このスクリプトをリポジトリに追加します。

{% code title="ci/start-device-protection.sh" overflow="wrap" %}
```bash
curl -fsSL https://github.com/AikidoSec/safe-chain/raw/refs/heads/main/install-scripts/install-endpoint-linux.sh | sh -s -- --container
aikido-endpoint-protection-start --wait-for-healthy
for f in /etc/profile.d/aikido-*.sh; do . "$f"; done
```
{% endcode %}

パッケージをインストールする各ステップの冒頭で、このスクリプトをsourceします。

{% code title="bitbucket-pipelines.yml" overflow="wrap" %}
```yaml
image: node:20-bookworm

pipelines:
  default:
    - step:
        name: Install dependencies
        script:
          - . ci/start-device-protection.sh
          - npm ci
```
{% endcode %}

* **`sh`で実行せず、`.`でsourceしてください。** sourceすることで、設定がステップの残りの部分でも維持されます。
* **すべてのステップで必要です。** 各ステップは新しいコンテナで実行されます。
* **ステップはrootとして実行する必要があり、イメージには`curl`が必要です。**

## Linux Shell runner

runnerホストに`--headless`を指定してエージェントをインストールし、再起動します。[Linux向けDevice Protectionのインストール](https://help.aikidogov.us/docs/docs-ja/aikido-device-protection/deploying-aikido-endpoint/device-protection-mdm-guides/linux/install-device-protection-for-linux#choose-the-install-flavor)を参照してください。

## 動作確認

{% code title="bitbucket-pipelines.yml" overflow="wrap" %}
```yaml
    - step:
        name: Verify Device Protection
        script:
          - . ci/start-device-protection.sh
          - curl -sS -o /dev/null -w "%{http_code}\n" --max-time 15 https://registry.npmjs.org/safe-chain-test/-/safe-chain-test-0.0.1-security.tgz
```
{% endcode %}

`403`は、エージェントがマルウェアテストパッケージをブロックしたことを意味します。`200`は、ダウンロードがエージェントを経由しなかったことを意味します。

## トラブルシューティング

| 問題                                                    | 対処法                                                       |
| ---------------------------------------------------------- | --------------------------------------------------------- |
| `Token is required`                                        | ステップから変数が参照できません。変数名を確認してください          |
| `Root privileges required`                                 | イメージが非rootユーザーで実行されています。rootで実行されるイメージを使用してください |
| テストパッケージが`200`を返す、または`SELF_SIGNED_CERT_IN_CHAIN` | スクリプトが`sh`または`bash`で実行されています。`.`でsourceしてください    |
