1# DLP Service Development
2
3The Data Loss Prevention (DLP) service is a system solution provided to prevent leakage of sensitive data. It provides a file format called DLP. A DLP file consists of the original file in ciphertext and the authorization credential, and ".dlp" is added to the end of the original file name (including the file name extension), for example, **test.docx.dlp**.
4
5A DLP file can be accessed only after a device-cloud authentication (network connection required) is successful. The permissions for accessing a DLP file include the following:
6
7- Read-only: The user can only view the file.
8- Edit: The user can read and write the file, but cannot change the permission on the file.
9- Full control: The user can read and write the file, change the permission on the file, and restore the plaintext of the file.
10
11When an app accesses a DLP file, the system automatically installs a DLP sandbox app for the app. As a twin app of the app, the sandbox app inherits data and configuration from the app, but is isolated from the app. The twin app is running in a DLP sandbox, which is restricted from external access to prevent data leakage. Each time a DLP file is opened, a sandbox app is generated. The sandbox apps are also isolated from each other. When an app is closed, its sandbox app will be automatically uninstalled and the temporary data generated in the sandbox directory will be cleared.
12
13Normally, the app is unaware of the sandbox and accesses the file in plaintext, like accessing a common file. However, the DLP sandbox restricts the app from accessing external resources (such as the network, clipboard, screenshot capturing, screen recording, and Bluetooth). For better user experience, you need to make adaptation for your app. For example, for a read-only file, you'd better hide the **Save** button and disable automatic network connection.
14
15## Sandbox Restrictions
16
17For an app in the DLP sandbox state, the permissions granted to the app are restricted based on the permission on the DLP file.
18
19| App Permission | Description | Read-Only | Edit/Full Control |
20| -------- | -------- | -------- | -------- |
21| ohos.permission.USE_BLUETOOTH | Allows an app to use Bluetooth. | Unavailable | Unavailable |
22| ohos.permission.INTERNET |Allows an app to access the Internet. |  Unavailable | Unavailable |
23| ohos.permission.DISTRIBUTED_DATASYNC | Allows an app to exchange user data (such as images, music, videos, and app data) with another device. | Unavailable | Unavailable |
24| ohos.permission.WRITE_MEDIA | Allows an app to read and write media files, such as images, videos, and audio clips. | Unavailable | Available |
25| ohos.permission.NFC_TAG | Allows an app to use NFC. | Unavailable | Available |
26
27## Available APIs
28
29| API | Description |
30| -------- | -------- |
31| isDLPFile(fd: number): Promise&lt;boolean&gt; <br> isDLPFile(fd: number, callback: AsyncCallback&lt;boolean&gt;): void| Checks whether a file is a DLP file. |
32| getDLPPermissionInfo(): Promise&lt;DLPPermissionInfo&gt; <br>getDLPPermissionInfo(callback: AsyncCallback&lt;DLPPermissionInfo&gt;): void  | Obtains the DLP permission information of this sandbox app. |
33| getOriginalFileName(fileName: string): string | Obtains the original name of a DLP file. |
34| getDLPSuffix(): string | Obtains the file name extension of this DLP file. |
35| on(type: 'openDLPFile', listener: Callback&lt;AccessedDLPFileInfo&gt;): void | Subscribes to the file open event of DLP files. The app will be notified when a DLP file is opened. |
36| off(type: 'openDLPFile', listener?: Callback&lt;AccessedDLPFileInfo&gt;): void | Unsubscribes from the file open event of DLP files. |
37| isInSandbox(): Promise&lt;boolean&gt; <br>isInSandbox(callback: AsyncCallback&lt;boolean&gt;): void | Checks whether this app is running in a sandbox. |
38| getDLPSupportedFileTypes(): Promise&lt;Array&lt;string&gt;&gt;<br>getDLPSupportedFileTypes(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void | Obtains the file name extension types that can be appended with .dlp. |
39| setRetentionState(docUris: Array&lt;string&gt;): Promise&lt;void&gt; <br> setRetentionState(docUris: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void | Sets the sandbox app retention state. If the retention state is set for a DLP file, the sandbox app will not be automatically uninstalled when the DLP file is closed. |
40| cancelRetentionState(docUris: Array&lt;string&gt;): Promise&lt;void&gt;<br> cancelRetentionState(docUris: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void | Cancels the sandbox app retention state. |
41| getRetentionSandboxList(bundleName?: string): Promise&lt;Array&lt;RetentionSandboxInfo&gt;&gt; <br> getRetentionSandboxList(bundleName: string, callback: AsyncCallback&lt;Array&lt;RetentionSandboxInfo&gt;&gt;): void  <br> getRetentionSandboxList(callback: AsyncCallback&lt;Array&lt;RetentionSandboxInfo&gt;&gt;): void| Obtains the sandbox apps in the retention state. |
42| getDLPFileAccessRecords(): Promise&lt;Array&lt;AccessedDLPFileInfo&gt;&gt; <br> getDLPFileAccessRecords(callback: AsyncCallback&lt;Array&lt;AccessedDLPFileInfo&gt;&gt;): void | Obtains the DLP files that are accessed recently. |
43|setSandboxAppConfig(configInfo: string): Promise&lt;void&gt;|Sets sandbox app configuration.|
44|getSandboxAppConfig(): Promise&lt;string&gt;|Obtains the sandbox app configuration.|
45|cleanSandboxAppConfig(): Promise&lt;void&gt;|Clears the sandbox app configuration.|
46| startDLPManagerForResult(context: common.UIAbilityContext, want: Want): Promise&lt;DLPManagerResult&gt; <br> | Starts the DLP manager app on the current UIAbility page in borderless mode (available only for the stage model). |
47
48## How to Develop
49
501. Import the [dlpPermission](../../reference/apis-data-protection-kit/js-apis-dlppermission.md) module.
51
52   ```ts
53   import { dlpPermission } from '@kit.DataProtectionKit';
54   ```
55
562. Open a DLP file. The system automatically installs a DLP sandbox app for your app. <br>Add the following code to your app:
57
58    ```ts
59    async OpenDlpFile(dlpUri: string, fileName: string, fd: number) {
60      let want:Want = {
61        "action": "ohos.want.action.viewData",
62        "bundleName": "com.example.example_bundle_name",
63        "abilityName": "exampleAbility",
64        "uri": dlpUri,
65        "parameters": {
66          "fileName": {
67            "name": fileName
68          },
69          "keyFd": {
70            "type": "FD",
71            "value": fd
72          }
73        }
74      }
75
76      try {
77        console.log('openDLPFile:' + JSON.stringify(want));
78        console.log('openDLPFile: delegator:' + JSON.stringify(this.context));
79        this.context.startAbility(want);
80      } catch (err) {
81        console.error('openDLPFile startAbility failed', (err as BusinessError).code, (err as BusinessError).message);
82        return;
83      }
84    }
85    ```
86
87    Add **ohos.want.action.viewData** to the **module.json5** file.
88
89    ```json
90      "skills":[
91        {
92          "entities":[
93            ...
94          ],
95          "actions":[
96            ...
97            "ohos.want.action.viewData"
98          ]
99        }
100      ]
101    ```
102
1033. Check whether the app is running in a sandbox.
104
105   ```ts
106   dlpPermission.isInSandbox().then((data)=> {
107     console.log('isInSandbox, result: ' + JSON.stringify(data));
108   }).catch((err:BusinessError) => {
109     console.log('isInSandbox: ' + JSON.stringify(err));
110   });
111   ```
112
1134. Obtain the permissions on the file. The permissions of the DLP sandbox app vary with the user's permission on the file. For more information, see [Sandbox Restrictions](#sandbox-restrictions).
114
115   ```ts
116   dlpPermission.getDLPPermissionInfo().then((data)=> {
117     console.log('getDLPPermissionInfo, result: ' + JSON.stringify(data));
118   }).catch((err:BusinessError) => {
119     console.log('getDLPPermissionInfo: ' + JSON.stringify(err));
120   });
121   ```
122
1235. Obtain information about the file name extension types that support the DLP solution. Based on the information obtained, you can learn what types of files can be used to generate DLP files.
124
125   ```ts
126   dlpPermission.getDLPSupportedFileTypes((err, result) => {
127     console.log('getDLPSupportedFileTypes: ' + JSON.stringify(err));
128     console.log('getDLPSupportedFileTypes: ' + JSON.stringify(result));
129   });
130   ```
131
1326. Check whether the opened file is a DLP file.
133
134   ```ts
135   import { dlpPermission } from '@kit.DataProtectionKit';
136   import { fileIo } from '@kit.CoreFileKit';
137   import { BusinessError } from '@kit.BasicServicesKit';
138
139   let uri = "file://docs/storage/Users/currentUser/Desktop/test.txt.dlp";
140   let file = fileIo.openSync(uri);
141   try {
142     let res = dlpPermission.isDLPFile(file.fd);  // Check whether the file is a DLP file.
143     console.info('res', res);
144   } catch (err) {
145     console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
146   }
147   fileIo.closeSync(file);
148   ```
149
1507. Subscribe to or unsubscribe from the DLP file open event.
151
152   ```ts
153   event(info: dlpPermission.AccessedDLPFileInfo) {
154     console.info('openDlpFile event', info.uri, info.lastOpenTime)
155   }
156   unSubscribe() {
157     try {
158       dlpPermission.off('openDLPFile', this.event); // Unsubscribe from the file open event.
159     } catch (err) {
160       console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
161     }
162   }
163   subscribe() {
164     try {
165       dlpPermission.on ('openDLPFile' , this.event); // Subscribe to the DLP file open event.
166     } catch (err) {
167       console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
168     }
169   }
170   onCreate() {
171    this.subscribe();
172   }
173   onDestroy() {
174    this.unSubscribe();
175   }
176   ```
177
1788. Obtain information about the DLP files that are recently accessed.
179
180   ```ts
181   async getDLPFileAccessRecords() {
182     try {
183       let res:Array<dlpPermission.AccessedDLPFileInfo> = await dlpPermission.getDLPFileAccessRecords(); // Obtain the list of recently accessed DLP files.
184       console.info('res', JSON.stringify(res))
185     } catch (err) {
186       console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
187     }
188   }
189   ```
190
1919. Obtain information about the DLP sandbox apps in the retention state.
192
193    ```ts
194    async getRetentionSandboxList() {
195      try {
196        let res:Array<dlpPermission.RetentionSandboxInfo> = await dlpPermission.getRetentionSandboxList(); // Obtain the sandbox apps in the retention state.
197        console.info('res', JSON.stringify(res))
198      } catch (err) {
199        console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
200      }
201    }
202    ```
203
20410. Set sandbox app configuration.
205
206    ```ts
207    async setSandboxAppConfig() {
208      try {
209        await dlpPermission.setSandboxAppConfig('configInfo'); // Set sandbox app configuration.
210      } catch (err) {
211        console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
212      }
213    }
214    ```
215
21611. Clear the sandbox app configuration.
217
218    ```ts
219    async cleanSandboxAppConfig() {
220      try {
221        await dlpPermission.cleanSandboxAppConfig(); // Clear the sandbox app configuration.
222      } catch (err) {
223        console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
224      }
225    }
226    ```
227
22812. Obtain the sandbox app configuration.
229
230    ```ts
231    async getSandboxAppConfig() {
232      try {
233        let res:string = await dlpPermission.getSandboxAppConfig(); // Obtain the sandbox app configuration.
234        console.info('res', JSON.stringify(res))
235      } catch (err) {
236        console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
237      }
238    }
239    ```
240
24113. Start the DLP manager app in borderless mode. This API can be called only in the UIAbility context and supports only the stage model.
242
243    ```ts
244    import { dlpPermission } from '@kit.DataProtectionKit';
245    import { common, UIAbility, AbilityConstant, Want } from '@kit.AbilityKit';
246    import { BusinessError } from '@kit.BasicServicesKit';
247
248    try {
249      let context = getContext () as common.UIAbilityContext; // Obtain the UIAbility context.
250      let want: Want = {
251        "uri": "file://docs/storage/Users/currentUser/Desktop/1.txt",
252        "parameters": {
253          "displayName": "1.txt"
254        }
255      }; // Request parameters.
256      dlpPermission.startDLPManagerForResult(context, want).then((res) => {
257        console.info('res.resultCode', res.resultCode);
258        console.info('res.want', JSON.stringify(res.want));
259      }); // Start the DLP manager app.
260    } catch (err) {
261      console.error('error', err.code, err.message); // Report an error upon a failure.
262    }
263    ```
264
26514. Check whether the current system provides the DLP feature.
266    ```ts
267    import { dlpPermission } from '@kit.DataProtectionKit';
268    import { BusinessError } from '@kit.BasicServicesKit';
269
270    dlpPermission.isDLPFeatureProvided().then((res) => {
271      console.info('res', JSON.stringify(res));
272    }).catch((err: BusinessError) => {
273      console.error('error', (err as BusinessError).code, (err as BusinessError).message); // Throw an error if the operation fails.
274    });
275    ```
276